flex子元素的宽度超出问题

469 阅读2分钟

在使用flex布局的时候,当设置display:flex的子元素超出容器宽度后,经常会出现一些问题。

  • 容器:wrap,宽度100px
  • 左边子元素:left,宽度设置为30px
  • 右边子元素:right,未设置宽度,所以其宽度为子元素的宽度,导致宽度超出100px
<div class="wrap">
    <div class="left"></div>
    <div class="right">
        <div class="right-content">
       adasdasdasdadasdasdasdasdasadasdasdasdadasdasadasdasdasdadasd
        </div>
    </div>
</div>
<style>
  .wrap{
    width: 100px;
    height: 100px;
    background-color: antiquewhite;
    display: flex;
  }
  .left{
    width: 30px;
    height: 50px;
    background-color: aqua;
  }
  .right{
    height: 50px;
    background-color: blueviolet;
  }
  .right-content{
    overflow: hidden;
  }
</style>

但最终在界面上显示的left宽度居然是0: image.png 设置display:flex后,子元素在没有超过指定宽度的时候,子元素的宽度是有效的,但超过指定宽度的话,子元素的宽度就无效了,子元素不能直接设置width: 30px。我们可以尝试找到原因,当wrap里的两个子元素按照项目大小分配空间之后,发现空间不足,由于flex-shrink默认是可以缩放的,所以将left进行了缩小。

按照这个思路,可以给left元素添加 flex-shrink: 0;使left子元素不进行缩放。或者直接写成flex: 0 0 30px;

.left{
    width: 30px;
    flex-shrink: 0;
    height: 50px;
    background-color: aqua;
 }
 // width: 30px 和 flex-shrink: 0 可以写成一句:flex: 0 0 30px;

根据修改后的代码,我们得到了下面的结果: image.png 到这,我们成功改变了left子元素的宽度,但是right子元素还有问题,但是这时right元素的flex-shrink应该就是默认缩放的呀,为什么会超出呢?

浏览器默认为flex容器的子元素设置了 "min-width: auto;min-height: auto", 即flex子元素的最小宽度高度不能小于其内容的宽高。

原来是因为right子元素的子元素宽度超出,导致right子元素的最小宽度过大,那按照这个思路,我们只需要覆写一下right子元素的min-width即可。

.right{
    min-width: 0;
    height: 50px;
    background-color: blueviolet;
 }

或者设置right子元素的overflow属性为auto或hidden也会得到正确的结果:

.right{
    overflow: auto;
    height: 50px;
    background-color: blueviolet;
 }

image.png