# 浮动清除方法

# 1.新增div设置clear:both

.container {
    border: 2px solid saddlebrown;
}
.box {
    height: 50px;
    width: 50px;
    background-color: aquamarine;
    float: left;
    margin: 20px;
}
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div style="clear:both;"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

可以理解为,最下方的未浮动的元素被包括在了container内,将浮动的元素也装了进去,所以解决了高度坍缩的问题

# 2.CSS伪元素

利用伪元素:after来完成上面新增了一个DIV完成的事

.container:after{
    content:".";
    display:block;
    height:0;
    visibility:hidden;
    clear:both;
}
/* 如果需要兼容IE6, 7 */
.container{zoom:1}
1
2
3
4
5
6
7
8
9

# 3.使父容器形成BFC

添加overflow:hidden;即可,详见BFC-IFC

# 4. display:table妙用

.container:after{
    content:"";
    display:table;
    clear:both;
}
1
2
3
4
5