伸缩布局flex
如果我们想让盒子无缝的摆在一行,在之前我们用的是float
实现的,使用浮动的话需要精确的计算盒子的宽度,以防止盒子掉下来。在这里使用伸缩布局不用考虑这一点,当设置父盒子为display: flex;
时,那么父盒子使用的就是伸缩布局。
假设有如下结构
<div class="father">
<div></div>
<div></div>
<div></div>
</div>
.father {
width: 600px;
height: 300px;
display: flex;
}
.father div {
flex: 1; /*每个人占一份,所以每个人占的是1/3*/
}
.father div:first-child {
background-color: pink;
}
.father div:nth-child(2) {
background-color: red;
}
.father div:last-child {
background-color: blue;
}
可见,父盒子已经被三等分了,因为每一个子盒子的flex
都是1
,如果将第二个子盒子的flex
改为2
,那个第二个盒子占2/4
,其余两个占1/4
.father div:nth-child(2) {
background-color: red;
flex: 2;
}
我们知道当设置margin
时,如果是float
,则需要重新考虑盒子的大小,以防盒子的布局出现问题,但是flex
布局不会,比如我设置第二个盒子的margin
值
.father div:nth-child(2) {
background-color: red;
margin: 0px 10px;
flex: 2;
}
可以发现第二个盒子减小了,以保证所占位置的大小。
除了可以在水平方向上分割,可以通过设置flex-direction: column;
来设置在垂直方向上分割
.father {
width: 600px;
height: 300px;
display: flex;
flex-direction: column;
}
这里取消第二个盒子的margin
值