可参考链接:CSS样式:外边距重叠及父子外边距重叠问题
关联:CSS边距折叠测试示例代码
代码
.clearfix::before,
.clearfix::after {
content: "";
display: table;
clear: both;
}
或者解决浮动高度塌陷的代码
.clearfix::after {
content: "";
display: block;
clear: both;
}
/* 相当于在最后面, 加上了个块盒
(比如div,并且加上clear:both也能实现同样的效果,但是不够优雅), 注意不能使用行盒 */
理解
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
width: 1000px;
background-color: #bfa;
padding: 30px; /* 添加padding,防止父子外边距合并 */
}
.item {
float: left;
width: 100px;
height: 100px;
color: #fff;
font-size: 1em;
text-align: center;
border: 2px solid red;
margin-bottom: 20px;
}
.normal {
background-color: #008c8c;
/* clear: left; */
/* margin-top: 351px; */
/* 上面clear: left, 就相当于设置了这里的margin-top
(但是不完全等于, 这里margin-top生效是因为容器写了padding,
隔绝了父子元素上外边距, 不然会把父元素给拉下来, 但是clear:left就没这个问题)
不能使用行盒!!! 因为行盒设置margin-top是无效的!!!所以下面normal类使用的元素是div,
*/
height: 0px; /* 高度也可以不设置0 */
}
</style>
</head>
<body>
<div class="container">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item">item10</div>
<div class="normal"></div>
</div>
</body>
</html>