在flex布局中如果每行展示4个盒子,左右两侧靠边,中间间距相同,可以选择的方法有很多,最容易想到的就是space-between,但是这种情况下需要给4个子盒子宽度,那么就不利于盒子封装,例如有时候可能一行是3个、有时候4个、或者5个展示位的时候,就需要重新写宽度,如果使用margin负值,就能解决这个问题。
使用方法为:
<div class="grandpa">
<div class="father">
<div class="son"><div></div> </div>
<div class="son"><div></div> </div>
<div class="son"> <div></div></div>
<div class="son"> <div></div></div>
</div>
</div>
<style>
.grandpa {
background-color: #d98081;
width: 1200px;
margin: 0 auto;
}
.father {
margin: 0 -10px;
border: none;
display: flex;
}
.son {
box-sizing: border-box;
background-color: #6e2a7f;
height: 100px;
width: 25%;
padding-left: 10px;
padding-right: 10px;
}
.son div {
width: 100%;
height: 100%;
background-color: #168578;
}
.son:nth-child(2),
.son:nth-child(4) {
background-color: #7f9781;
}
</style>
这时,仅grandpa盒子有宽度,其他盒子的宽度都可以自动设置,我们只需要确定每行需要几个盒子,如果每行4个盒子则设置son的宽度为25%,每行为5个盒子则设置son的宽度为20%,以此类推。
这样做的原理就是给了father盒子左右两侧负margin值后,father盒子宽度变大,margin值的负数和每行son盒子最左侧盒子的左padding,最右侧盒子的右padding抵消,从而使两侧和grandpa合资对齐。