常用的清除浮动的三种方法

132 阅读1分钟

1、给受到浮动影响的元素添加overflow:hidden。

原因:overflow属性会触发BFC

BFC:block(块级) formatting(格式化) context(上下文)的简写,

意思是:以块级元素的排列规则在当前环境中排列

<style>
        .box1{
            width: 100px;
            height: 100px;
            background-color: #f00;
            float: left;
        }
 
        .box2{
            width: 200px;
            height: 200px;
            background-color: #0f0;
            /* float: left; */
            overflow: hidden;
        }
</style>

2、在受到浮动影响的元素前面添加一个空div:clear:both;清除浮动带来的影响。

<div class="box1"></div>
<div class="clearFix"></div>
<div class="box2"></div>

3、在浮动元素的父标签的伪类选择器:after中清除浮动 - 类似于空div的格式。

.box:after{
          content:"";
          display: block;
          clear:both;
}