下面代碼來自MDN
html部分:
<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>
css部分:
#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; }
效果部分:
以上代碼描述,id為content容器中有5個小盒,content容器定寬500px,
每個小盒的初始內容寬度是120px + 邊框3px * 2 = 126px,
現在前三個小盒flex-shrink數值為1,后兩個數值為2,下面計算:
小盒初始寬度總和與content容器寬度差值
Δ = 126 * 5 - 500 = 130
收縮指數
Δt = 130 ÷ (1*3 + 2*2)
前三個盒子寬度
box = 126 - Δt
后兩個盒子寬度
box1= 126 - 2Δt
*總結:
1、flex-shrink僅在內容默認寬度之和大於容器的時候才會有效
2、容器內子容器的content、border、padding都要參與計算才能得到正確的收縮指數值
3、border和padding即使參與了計算,但寬度始終不會改變,假如收縮后的總寬度仍然超過容器寬度,則會超出盒子,即使設置box-sizing為border-box也不能使border和padding收縮