在很多前端工程师日常工作中,在使用到float布局时,总会有一点需要去考虑的,那就是清除浮动问题。
那这个问题怎么会发生的呢?
当float子元素高度超出父级元素高度时,父级元素高度塌缩,因为float元素脱离文档流,其布局不受父元素控制
这个情况如下图所示

代码如下:
<style>
.wrap {
padding: 30px;
background: #CECECE;
color: #FFFFFF;
text-align: center;
line-height: 100px;
}
.left {
float: left;
background: #00A8FE;
width: 300px;
height: 200px;
padding: 10px;
text-align: center;
line-height: 200px;
color: #FFFFFF;
opacity: 0.3;
}
.right {
float: right;
background: #9ACD32;
width: 300px;
height: 200px;
padding: 10px;
text-align: center;
line-height: 200px;
color: #FFFFFF;
opacity: 0.3;
}
</style>
<article class="wrap">
wrap
<div class="left">left</div>
<div class="right">right</div>
</article>
那这个问题怎么解决呢?
1. clear:both
在父级元素内部加个div,设置clear: both即可,清除两边的浮动。
<style>
...
.clear {
clear: both;
}
</style>
<article class="wrap">
wrap
<div class="left">left</div>
<div class="right">right</div>
<div class="clear"></div>
</article>
2. overflow:hidden
<style>
...
.wrap {
overflow: hidden; // auto也可以,但是切记visible不行
}
...
</style>
<article class="wrap">
wrap
<div class="left">left</div>
<div class="right">right</div>
</article>
3. :after伪元素
<style>
...
.wrap:after {
clear: both; // auto也可以,但是切记visible不行
}
...
</style>
<article class="wrap">
wrap
<div class="left">left</div>
<div class="right">right</div>
</article>
这里有个伪元素的知识点:
:before和:after是分别在当前元素内部的前后插入两个元素块。
这里再wrap类后价格:after伪元素,其实和解决方案一一样,在内部的最后加一个元素,里面使用clear:both从而达到清除浮动的效果。
清除浮动后效果:
