问题

子元素和父元素相邻的垂直外边距会发生重叠,子元素的外边距会传递给父元素,使用空的table标签可以隔离父子元素的外边距,阻止外边距的重叠

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div class="box1 clearfix">
<div class="box2"></div>
</div>
对应的样式:
.box1{
width: 300px;
height: 300px;
background-color: #bfa;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
margin-top: 100px;
}

解决措施

通过设置父元素的before伪类来解决,display:table可以将一个元素设置为表格显示

1
2
3
4
5
.box1:before{
content: "";
/* display:table可以将一个元素设置为表格显示 */
display: table;
}

解决完父元素与子元素垂直外边距重叠之外,可能还会出现父元素高度塌陷的问题,设置父元素after伪类来解决

1
2
3
4
5
.clearfix:after{
content: "";
display: block;
clear: both;
}
优化一下代码
1
2
3
4
5
6
.clearfix:before,
.clearfix:after{
content: "";
display: table;
clear: both;
}