1.额外标签法
在最后一个浮动标签后面,添加一个额外的标签,设置为clear:both;属性
适合用于清除兄弟元素间的浮动
<style>
.son{
width: 100px;
height: 100px;
float: left;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
.clearfix{
clear: both;
}
</style>
<div class="son1 son" style="background-color: aqua;"></div>
<div class="son2 son" style="background-color: aquamarine;"></div>
<!-- 清除浮动的额外盒子 -->
<div class="clearfix"></div>
<div class="box"></div>
2.父级添加overflow属性
将父元素添加overflow:hidden;属性
只适合父子元素之间清除浮动,不适合含有内容较多的父级(容易导致内容隐藏,无法显示要溢出的元素)
<style>
.father{
overflow: hidden;
}
.son {
width: 100px;
height: 100px;
float: left;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="father">
<div class="son1 son" style="background-color: aqua;"></div>
<div class="son2 son" style="background-color: aquamarine;"></div>
</div>
<div class="box"></div>
注:上述代码中,如果.box的div位于.father的div内部(不是作为兄弟元素),还是会被浮动覆盖
3.使用after伪元素清除浮动
给浮动元素的父元素的伪元素添加相应属性
只适合父子元素之间清除浮动(如果.box的div位于.father的div内部,和上一种方法一样还是会被浮动覆盖)
<style>
.clearfix::after{
content: '';
display: block;
clear: both;
visibility: hidden;
}
.son {
width: 100px;
height: 100px;
float: left;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="father clearfix">
<div class="son1 son" style="background-color: aqua;"></div>
<div class="son2 son" style="background-color: aquamarine;"></div>
</div>
<div class="box"></div>