当一个父容器中的子元素变为浮动后,父容器就会坍塌,下面的盒子也会就此补充上来
因此,为了解决这样的问题,就有了清除浮动的几种方案:
<!-- 清除浮动 -->
<div class="container">
<div class="inner"></div>
</div>
<style>
html, body {
margin: 0;
padding: 0;
}
.container {
width: 100%;
background-color: gold;
}
.inner {
background-color: tomato;
height: 30px;
width: 40px;
float: left;
}
</style>
此时,父容器已经坍塌:
变成
解决办法有以下几种:
(1)创建BFC
.clearfix-1 {
overflow: hidden;
}
.clearfix-2 {
overflow: auto;
}
缺点是超出盒子外的部分就被隐藏掉了,所以这个需要在合适的场景中使用
(2)使用clear:both
利用伪元素,作用在父容器上:
.clearfix-3 {}
.clearfix-3:after {
content: "";
display: block;
clear: both;
}
或者创建一个br、hr放在浮动元素后
<!-- 清除浮动 -->
<div class="container">
<div class="inner"></div>
<br class="clearfix-4">
</div>
<style>
.clearfix-4 {
clear: both;
}
</style>
至于为什么clear:both有这个能力呢,todo