Skip to content

CSS flex

ythy edited this page Apr 30, 2019 · 3 revisions

flex属性分三个部分

flex-grow

如何填充一行的剩余空间

  • 0 (Default value) Do not stretch. Either size to element's content width, or obey flex-basis.
  • 1 Stretch.
  • ≥2 (integer n): Stretch. Will be n times the size of other elements with flex-grow: 1 on the same row.

flex-shrink

元素超出一行空间的时候,缩放的比例, 当子元素设置flex-shrink为0时,可以超出容器宽度
works similarly to flex-grow: it dictates how much the element should shrink when the sum of initial/original widths on the same row exceeds the available space along the cross axis.
Setting it to 0 prevents collapsing beyond their minimum widths (usually restricted by content in each element), while dimensionless integer values allows collapsing: 1 will enable collapsing, and n allows you to set ratios on how far each element collapses relative to 1 例:

#main {
    width: 300px;
    height: 100px;
    border: 1px solid #c3c3c3;
    display: flex;
}

#main div {
    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: 110px;
}

#main div:nth-of-type(1) {
    flex-shrink:4;
}

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;"></div>
  <div style="background-color:khaki;"></div>
</div>

行宽为300, 3个子元素宽默认110,flex-shrink属性 分别为 4 1 1
子元素总宽度为330,超过了行宽300,超出的30部分通过 4 1 1的比例进行压缩,后得到的宽度比为20 5 5
3个子元素分别减去这个压缩的数值后,由110 110 110变为 90 105 105,合计300,计算完成。

flex-basis

设置元素初始宽度 When you set conflicting width and flex-basis, flex-basis is used. Actually, the only time width is used is when flex-basis is set to auto, which is default. Set it to whatever and it will apply.

conclusion

  • 实际应用当中 flex: 1 的容器如果不设置 overflow: hidden的话 容器子元素过宽或者过高,容器实际宽度或高度是会按子元素伸缩的
  • flex的属性默认是 flex: 0 1 auto, 即不会延展,但是会收缩,如果设置了display: flex的父容器中的子容器都没有显式设置flex 属性的话, 如果其中一个子容器过大,另一个子容器相对过小并设置了overflow: hidden, 会导致过小的容器压缩的更小,以致于页面上不显示 如果过小的容器没有设置overflow: hidden,那他的大小会超过比例宽度,而正常显示
Clone this wiki locally