关于flex布局,基本的属性还是比较容易理解的,本文仅仅是来讨论shrink和grow两个属性
相信大家肯定用过下面这句代码
.test{
flex: 1
}
仅仅定义了一个flex,其实它是三个属性的缩写
flex-grow
flex-shrink
flex-basis
1.flex-grow
那我们来看看仅仅定义flex:1这个具体会怎么计算
.content {
display: flex;
width: 1200px;
height: 300px;
background: green;
}
.child1 {
flex: 1;
background: red;
}
.child2 {
flex: 2;
background: orange;
}
.child3 {
flex: 3;
background: gray;
}
<div class="content">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
</div>
我们来看看最后每一个child计算出的值是啥



由此可见,只定义一个值时,其实是定义了flex-grow,这个时候,每一个子元素的宽度会等比例分配,比如上面的代码,1+2+3总共分成了6份,那么第一个的宽度就是12001/6,第二个是12002/2,第三个是1200*3/6
上面的代码,基准值都是0%,那么宽度就是按照flex-grow来分配的,假如我们给每一个dom定义基准值,看看会是什么效果
.child1 {
flex: 1 1 200px;
background: red;
}
.child2 {
flex: 2 1 300px;
background: orange;
}
.child3 {
flex: 3 1 400px;
background: gray;
}
这是基准值总和为200+300+400=900,小于父容器的大小,那么就会根据grow的比率来平分剩余的部分300,child1分到300*1/6=50,最后大小为250,child2分到300*2/6=100,最后大小为400,child3分到300*3/6=150,最后大小为550
2.flex-shrink
把代码再改一下
.child1 {
flex: 1 1 500px;
background: red;
}
.child2 {
flex: 2 1 400px;
background: orange;
}
.child3 {
flex: 3 1 600px;
background: gray;
}
此时,基准值为500+400+600=1500,大于1200,多出了300,此时就需要对多余的部分进行压缩了,计算公式如下
flex-basis - 多出的值 * (flex-basicflex-shrink) /(所有的子节点自己的基准值再相加),那么
child1: 500 - 300 * 500 * 1/(500*1 +400*1 + 600*1) = 500 -300*500/1500 =500-100 = 400
child2: 400 - 300*400*1/(500*1+400*1+600*1) = 400 -300*400/1500 = 400 - 80=320
child3: 600 - 300*600*1/(500*1+400*1+600*1) = 600 - 300*600/1500 = 600 - 120 = 480
可以把shrink修改一下再计算试试
.child1 {
flex: 1 2 500px;
background: red;
}
.child2 {
flex: 2 3 400px;
background: orange;
}
.child3 {
flex: 3 5 600px;
background: gray;
}
多出了1200 - 500-400-600 = 300
child1: 500 - 300*(500*2) / (500*2 + 400*3 + 600*5) = 500 - 300 * 1000 / 5200 = 442
child2: 400 - 300 * (400*3) / 5200 = 330
child3: 600 - 300 * (600*5) / 5200 = 426
网友评论