以flex为基础,最小和最大宽度溢出

时间:2017-12-21 19:09:37

标签: html css css3 flexbox

我的目标是使用flexbox来实现具有给定宽度的滑块,并且可以在项目(图像)添加到其中时增长,直到达到特定宽度。达到该宽度后,我想在x轴上显示滚动条。我还希望滑块不会缩小到最小宽度。

这是我试过的:

HTML:

<div class="wrapper">
  <div class="thisDivAllowsSliderToGrowToMaxWidth">
    <div class="slider">
      <div class="image"></div>
      ...
    </div>
  </div>
</div>

CSS:

.wrapper {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items:center
}

.slider {
  display:flex;
  justify-content:flex-start;
  height:100px;
  flex-basis: 250px;
  min-width:200px;
  max-width:350px;
  overflow-x:auto;
}

.image {
  flex-shrink:0;
  height:100px;
  width:50px;
}

弹出的问题是,只要overflow-x被添加到滑块,它就不会再增长,但只要达到弹性基础宽度就会显示滚动条。

有趣的是,在滑块周围添加一个简单的包装div(.thisDivAllowsSliderToGrowToMaxWidth)可以解决这个问题。您可以找到示例here

任何人都可以回答为什么会发生这种情况,我是否按预期使用了flex属性?

1 个答案:

答案 0 :(得分:2)

要根据弹性项目的宽度使弹性容器增长,您可以将flex-basis设置为content

content会根据弹性项目的内容自动调整大小

&#13;
&#13;
$(".add-slide").on("click",function(){

$(".slider").append('<div class="image"></div>');

});
&#13;
    .wrapper {
      height: 300px;
      border :1px solid red;
      display: flex;
      justify-content: center;
      align-items:center
    }

    .slider {
      display:flex;
      border: 1px solid black;
      height:100px;
      flex-basis: content;
      min-width:200px;
      max-width:350px;
      overflow-x:auto;
      overflow-y:hidden;
    }

    .image {
      flex-shrink: 0;
      border: 1px solid green;
      height:100px;
      width:50px;
    }

    button {
      margin-bottom: 20px;
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
<button class="add-slide">add slide</button>

<div class="wrapper">
    <div class="slider">
        <div class="image"></div>
    </div>
</div>
    
    
&#13;
&#13;
&#13;