css3 高级特性(5):flex=1暗藏玄机

225 阅读1分钟

flex=1 就是flex:1 1 0%

知识储备:

flex:flex-grow flex-shrink flex-basis

flex-grow:如果子元素的width(height)值总和 < 容器的宽(高)时,增加子元素的width(height)

flex-shrink:如果子元素的width(height)值总和 > 容器的宽(高)时,减少子元素的width(height)

flex-basis:子元素指定的宽(高)

  • flex 默认是: 0 1 auto
  • flex=0 ; 0 1 0%
  • flex=auto; 11 auto
  • flex=none; 0 0 auto

html代码

<div class="container">
    <div class="text_a">A </div>
    <div class="text_b">B 我有很多元素</div>
    <div class="text_c">C 我的内容是最多的 我的内容是最多的 我的内容是最多的</div>
</div>

css代码

.container{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    height: 300px;
}
.text_a{
    background: darkcyan;
}
.text_b{
    background:rosybrown ;
}
.text_c{
    background:burlywood ;
}

研究一下 flex:1 和 flex:1 1 auot

现在总是习惯于使用flex布局,有时候往往忽略了某些细节,由于项目中做布局,才发现 flex:1 不等于flex:1 1 auto,其中牵扯到是flex-basis的知识。

flex-basis=0% 和 flex-basis=auto 区别

  • flex-basis:auto 表示项目的本来大小,也就是完全根据子列表项自身尺寸渲染

    • 如果 width(height) 值 = auto,基于 flex 的元素的内容自动调整大小
  • 如果 width(height) 值 != auto,根据主轴方向检索该 flex-item 的 ,flex-basis=width(height) 值
  • flex-basis: 0% 相当于指定了宽度或高度(由主轴方向决定)为 0。

flex:1 (flex:1 1 0%)

.text_a,.text_b,.text_c{
    padding: 10px;
    flex:1;
}

运行效果

image-20220610111239498.png

flex:1 1 auto

.text_a,.text_b,.text_c{
    padding: 10px;
    flex: 1 1 auto;
}

image-20220610112107552.png

flex 1 1 auto + width:200px

.text_a,.text_b,.text_c{
    padding: 10px;
    flex: 1 1 auto;
    width: 200px;
}

image-20220610112305255.png

结语

如果对本文有任何疑问,欢迎提问哦 如果本文对你有一丁点帮助,点个赞支持一下吧,感谢感谢

本文将同步到个人公众号:言字(欢迎关注👏)

GIF 2022-6-7 21-39-18.gif