清除浮动的四种方法

184 阅读1分钟
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
            width: 300px;
            border: 1px solid #000;
        }

        .big {
            float: left;
            width: 150px;
            height: 150px;
            background-color: pink;

        }

        .small {
            float: right;
            width: 110px;
            height: 110px;
            background-color: skyblue;
        }

        .footer {
            width: 1000px;
            height: 50px;
            background-color: deeppink;
        }

        .clear {
            clear: both;
        }
    </style>
</head>


<body>
    <div class="father">
        <div class="big">大盒子</div>
        <div class="small">小盒子</div>
        <div class="clear">我是额外的标签</div>
    </div>
    <div class="footer"></div>
</body>

</html>

1.额外标签法(在最后一个浮动标签后,新加一个标签,给其设置clear:both;)(不推荐)

优点:通俗易懂,方便

缺点:添加无意义标签,语义化差

不建议使用。

2.父级添加overflow属性(父元素添加overflow:hidden)(不推荐)

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

.fahter{
    width: 400px;
    border: 1px solid deeppink;
    overflow: hidden;
}

优点:代码简洁

缺点:内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素

不推荐使用

3.使用after伪元素清除浮动(推荐使用)

.clearfix:after{/*伪元素是行内元素 正常浏览器清除浮动方法*/
    content: "";
    display: block;
    height: 0;
    clear:both;
    visibility: hidden;
}
.clearfix{
    *zoom: 1;/*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行*/
}
big
small
优点:符合闭合浮动思想,结构语义化正确

缺点:ie6-7不支持伪元素:after,使用zoom:1触发hasLayout.

推荐使用

4.使用before和after双伪元素清除浮动

 .clearfix:after,.clearfix:before{
    content: "";
    display: table;
}
.clearfix:after{
    clear: both;
}
.clearfix{
    *zoom: 1;
}
big
small
优点:代码更简洁

缺点:用zoom:1触发hasLayout.

推荐使用