说说 flex-shrink 属性的规则

问题

面试题:你能说说 flex-shrink 么?

我们所知 flex 语法如下

flex: <flex-grow> <flex-shrink> <flex-basis>

并且可以有一些缩写

flex: 1

# 等效于

flex: 1 0 0

其中 flex-grow 比较好理解,但是 flex-shrink 关注的就比较少了,正好笔者面试时被问到,一时间想不起来,就查一查并做个笔记

分析

先看一段代码,摘录自 MDN

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #content {
            display: flex;
            width: 500px;
        }

        #content div {
            flex-basis: 120px;
        }

        .box { 
            flex-shrink: 1;
        }

        .box1 { 
            flex-shrink: 2; 
        }
    </style>
</head>
<body>
    <p>the width of content is 500px, flex-basic of flex item is 120px.</p>
    <p>A, B, C are flex-shrink:1. D and E are flex-shrink:2</p>
    <p>the width of D is not the same as A's</p>
    <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>
</body>
</html>

他的效果是这样的

为什么 A、B、C 元素写了 flex-shrink: 1; 占 105 px,而 D、E 元素 flex-shrink: 2; 占 91px?

给出收缩公式

子项收缩宽度 = 子项收缩比例 * 溢出宽度
子项收缩比例 = (子项宽度 * 子项flex-shrink) / 所有(子项的宽度 * flex-shrink系数)之和

代入公式,计算 A 的宽度,

// 有 3 个 A 一样的权重和宽度,有两个 E 一样的权重和宽度
所有(子项的宽度 * flex-shrink系数)之和 = (120 * 1 * 3 + 120 * 2 * 2) = 840

子项收缩比例 = (120 * 1) / 840 = 0.142857

// 子项目本应该占 120 * 5 的宽度,但父容器只有 500,相减得溢出宽度。
溢出宽度 = ( 120 * 5 - 500) = 100

子项目收缩宽度 = 0.142857 * 100 = 14.2857

A 的真实宽度为 = 120 - 14.2857 = 105.72px

那么 E 的宽度计算规则类似

子项收缩比例 = (120 * 2) / 840 = 0.285714
子项目收缩宽度 = 0.285714 * 100 = 28.5714
E 的真实宽度为 = 120 - 28.5714 = 91.4286
posted @ 2020-05-22 15:10  Ever-Lose  阅读(793)  评论(0编辑  收藏  举报