关于flex-shrink那些事

63 阅读2分钟

今天在项目中使用到flex,父元素固定宽度,第一个子元素也需要固定宽度,第二个元素根据第一个元素的高度自适应,给出的解决方案是flex,flex-shrink,就去仔细看了一下shrink的计算规则。

在查询的过程中发现有很多说得并不准确,包括一些比较大的教程平台,阅读量并不低

这里附上我的一些理解,例子以mdn官方提供的为例

    <div id="content">
        <div class="box" style="background-color:red;">A</div>
        <div class="box" style="background-color:lightblue;">B</div>
        <div class="box" style="background-color:yellow;">C</div>
        <div class="box1" style="background-color:brown;">D</div>
        <div class="box1" style="background-color:lightgreen;">E</div>
    </div>
        #content {
            display: flex;
            width: 500px;
        }

        #content div {
            flex-basis: 120px;
            border: 3px solid rgba(0, 0, 0, .2);
        }

        .box {
            flex-shrink: 1;
        }

        .box1 {
            flex-shrink: 2;
        }
  1. 每个元素宽度分别为 w1 w2 w3 w4 w5 ====> 每个均为120px
  2. 每个元素的shrink分别为 a, b, c, d, e ===> 1,1,1,2,2
  3. 超出宽度为 A = w1+w2+w3+w4+w5 - 父元素宽度 = 120+120+120+120+120 - 500 = 600px-500px = 100px
  4. 总压缩权重 W = a * w1 + b * w2 + c * w3 + dw4+ ew5 = 1201 + 1201+ 1201 + 1202 + 120*2 = 840
  5. 压缩率 S = a(flex-shrink)的值 * 宽度(w1) / 总压缩权重W; (这里以计算第一个为例子) 120 * 1/840 约等于 0.1428
  6. 最终结果宽度 = 本身宽度w1 - S * 超出宽度A ; 120 - 120 * 1/840 *100 = 120 - 14.28 = 105.75px

因为例子中为每个div设置border,所以计算宽度时应该加上宽度,每个元素宽度为126px,计算结果如下(还是以第一个为例):

  • 总宽度:126 * 5 = 630
  • 超出宽度:126 * 5 - 500 = 630 - 500 = 130
  • 总压缩权重:126 * 1 +1261+1261 +1262+1262 = 378 + 504 = 882
  • 压缩率:126 * 1 / 882 = 0.1428
  • 最终结果:126 - 126 * 1/882 *130 = 126 - 18.57= 107.43

希望对大家在使用时有帮助,在使用时尽量找官方的文档,或者多对比几篇,自己动手实验找到正确的结果。