清除浮动的hack方法
代码实现
<style>
.parent {
background-color: gray;
}
.parent::before {
display: table;
content: ' ';
}
.parent::after {
display: table;
content: ' ';
clear: both;
}
.parent .children {
float: left;
margin-top: 100px;
width: 500px;
height: 250px;
background-color: lightblue;
}
</style>
<div class="parent">
<div class="children"></div>
</div>
效果预览:
58dc7914438a7f5db67bdfbb904df8bb
原理解析
在parent类上使用::before
::after
生成伪元素并将它们的display设置为table. 这会创建一个匿名表格单元格和一个新的块格式化上下文,这意味着:before
伪元素可以防止上边距折叠。:after
伪元素用于清除浮动。