说说 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; 占 107px,而 D、E 元素 flex-shrink: 2; 占 88px?

因为容器 content 占 500px,而 A、B、C、D、E 的 flex-basis 需要 120px,也就是要 600px 宽的容器才能放下这些元素,空间不够分时 flex-shrink 发挥了作用。

600 - 500 = 100px,所以五个元素需要共同腾挪出 100px 的大小,怎么个缩小法就得看 flex-shrink 的分配。五个元素的 flex-shrink 之和为 7,那么每个 flex-shrink 单位得 100 / 7 = 14.2857px

那么 A 真实所占就是 120 - 14.2857 = 105.72px,E 真实所占就是 120 - 2 * 14.2857 = 91.42px

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章