和FlexBox彈性盒子計算規則相關的屬性有:javascript
margincss
flex-basishtml
flex-growjava
flex-shrinkflex
Flex容器每一行的寬度 = 每一個子容器的寬度 + 子容器margin-left和margin-right的值code
html: <div class='container'> <div class='item first' style='background-color:coral;'></div> <div class='item second' style='background-color:lightblue;'></div> <div class='item third' style='background-color:khaki;'></div> </div> css: .container { display: flex; width: 400px; } .item { height: 40px; } .first { flex: 1 0 0; background-color: red; } .second { flex: 2 0 0; background-color: blue; margin: 0 50px; } .third { flex: 3 0 0; background-color: yellow; }
總width
(400px) = 總margin
(100px) + 每一個item的寬度
;htm
因爲flex-basis
屬性值爲0,剩餘空間爲400px
,則各個子盒子會根據自身的flex-grow
屬性值及所佔總比重來分配剩餘空間
.first寬度: 400*(1/(1+2+3))
.second寬度: 400*(2/(1+2+3))
.third寬度: 400*(3/(1+2+3))
ip
子盒子的基準值it
能夠代替申明width
屬性class
同時聲明width
屬性和flex-basis
屬性時,會以flex-basis
的值來計算
當flex-basis
屬性值爲0
,在width
有申明的狀況下以width
來計,width
沒有的申明的話,則按其內容來計。
flex-grow
申明的值爲0,不出現伸展的狀況
flex-grow
申明的值不爲0,且子盒子的flex-basis
(或width)值之和 < 容器的padding的左邊界到右邊界的值。那麼子盒子會根據申明的flex-grow
值去分配剩餘的空間。
分配規則是按子盒子flex-grow
屬性值所佔百分比來分配: demo見上
<div class='container'> <div class='item first' style="background-color:coral;"></div> <div class='item second' style="background-color:lightblue;"></div> <div class='item third' style="background-color:khaki;"></div> </div> .container { display: flex; width: 200px; height: 400px; border: 1px solid #c3c3c3; } .first { flex-basis: 40px; flex-shrink: 1; } .third { flex-basis: 40px; flex-shrink: 2; } .second { flex-shrink: 3; width: 200px; }
首先依據flex-basis屬性
計算各個彈性盒子的寬度值,(200+40+40)px
,一共溢出了80px
。
而後依據各個彈性盒子的flex-shrink
屬性值,算出其加權後的綜合值:1*40 + 2*40 + 3*200 = 720(px)
;
.first須要縮小的值:(40\*1/720)*80
約等於4px
.second須要縮小的值:(40\*2/720)*80
約等於9px
.third須要縮小的值:(200\*3/720)*80
約等於67px
第一個盒子的寬度40-4 = 36px
第二個盒子的寬度40-9 = 31px
第三個盒子的寬度200-67 = 133px
若是flex-basis
的屬性未設置,即flex-basis: 0
,那麼彈性盒子計算多餘空間或者溢出空間的寬度是依據其width
的值,若是width
未設置,那麼是其內容的寬度
若是同時設置了flex-basis
的屬性值和width
的值,那麼將會忽略width
的值
flex-basis
可設爲百分比,是相對於祖先申明爲display:flex
的元素而言
flex: 1; -->> flex: 1 1 0%;
flex: none; -->> flex: 0 0 auto;
flex: auto; -->> flex: 1 1 auto;
flex: 0 auto;或者 flex: initial -->> flex: 0 1 auto; 即爲flex的初始值