和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的初始值