問題
面試題:你能說說 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