有没得发现这两功能一样的,不知道各位平时都习惯用哪个。首先,flex 属性是 flex-grow、flex-shrink 和flex-basis 属性的简写属性 ,通常我们认为flex-grow:1;与flex:1;是同一个意思,就是将子元素瓜分父容器的剩余空间1份。
那么你是不是有一个疑问,都能分配空间,那么到底有什么区别呢???
重点来了!!!!!这两个属性在放大时的计算方式不一样。
flex-grow是对“父容器大小减去原本每个容器大小之和后的”的空间进行比例分配的。
比如下方例子,父容器宽600,子容器原本应该是每个100px,全部排列后剩余600-300=300,再对这300进行1:2的分配。所以一个分得100,一个分得200,加上原本的大小就是一个200,一个300。
flex是对“父容器大小减去你没有flex的子容器的剩余全部大小”进行比例分配的。比如下方例子,父容器宽600,这里有一个没有flex的子元素,它的大小是100,那么剩余空间600-100=500,再对这500进行1:2的分配。所以一个分配100,一个分配200。
可以结合下面两个情况仔细区别。
1.flex-grow
<article>
<div>flex-grow: 1;
<p>200px</p>
</div>
<div>flex-grow: 2;
<p>300px</p>
</div>
<div>3
<p>100px</p>
</div>
</article>
<style>
article {
width: 600px;
height: 200px;
margin: 50px auto;
display: flex;
border: 1px dashed black;
}
div {
width: 100px;
height: 100px;
}
div:nth-child(1) {
flex-grow: 1;
background-color: darkorange;
}
div:nth-child(2) {
flex-grow: 2;
background-color: skyblue;
}
div:nth-child(3) {
background-color: thistle;
}
</style>
结果图:
2.flex
<article>
<div>flex-grow: 1;
<p>166.66px</p>
</div>
<div>flex-grow: 2;
<p>333.34px</p>
</div>
<div>3
<p>100px</p>
</div>
</article>
<style>
article {
width: 600px;
height: 200px;
margin: 50px auto;
display: flex;
border: 1px dashed black;
}
div {
width: 100px;
height: 100px;
}
div:nth-child(1) {
flex: 1;
background-color: darkorange;
}
div:nth-child(2) {
flex: 2;
background-color: skyblue;
}
div:nth-child(3) {
background-color: thistle;
}
</style>
效果图: