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