# 清除浮动的几种方式

clear:both:本质就是闭合浮动, 就是让父盒子闭合出口和入口,不让子盒子出来

  • 伪类清除:after(推荐使用)
    优点:符合闭合浮动思想,结构语义化正确
    缺点:ie6-7不支持伪元素:after,使用zoom:1触发hasLayout.
    注意: 给父类添加clearFix
    <div class="floatParent clearFix">
        <div class="floatChild">
            floatChild
        </div>
    </div>
1
2
3
4
5
.clearFix:after {
  content: "";
  display:block;
  clear: both;
}
.clearFix {
*zoom : 1;
}
1
2
3
4
5
6
7
8
  • 使用before和after双伪元素清除浮动
    注意: 给父类添加clearFix
.clearFix:before, .clearFix:after {
    content: "";
    display: table;
}
.clearFix:after {
    clear: both;
}
.clearFix {
    *zoom:1;
}
1
2
3
4
5
6
7
8
9
10
  • 新建dom使用clear:both
    注意: 给谁清除浮动,就在其后额外添加一个空白标签。
<div class="floatParent">
    <div class="floatChild">
        floatChild
    </div>
    <div class="clearFix"></div>    
</div>
1
2
3
4
5
6
.floatChild {
    float: left;
}
.clear{
  clear:both;
}
1
2
3
4
5
6
  • 父级添加overflow属性(父元素添加overflow:hidden)(不推荐)
    优点:代码简洁
    缺点:内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素

通过触发BFC,实现清除浮动

.floatParent {
    overflow: hidden;
}
1
2
3
最后更新时间: 6/20/2022, 10:48:50 PM