css清除浮动

什么时候清除浮动?

1.父级没高度
2.子盒子浮动了
3.影响下面布局了,我们就应该清除浮动了

清除浮动方法

额外标签法(隔墙法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
.son {
float: left;
weight: 100px;
height: 100px;
background-color: #0f0;
}
.clearfix {
clear: both;
}
.another {
width: 700px;
height: 150px;
background-color: #000;
}
</style>
<div class="father">
<div class="son"></div>
<div class="clearfix"></div>
</div>
<div class="another"></div>

父级overflow: hidden;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<style>
.father {
overflow: hidden;
}
.son {
float: left;
weight: 100px;
height: 100px;
background-color: #0f0;
}
.another {
width: 700px;
height: 150px;
background-color: #000;
}
</style>
<div class="father">
<div class="son"></div>
</div>
<div class="another"></div>

父级after伪元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<style>
.son {
float: left;
weight: 100px;
height: 100px;
background-color: #0f0;
}
.another {
width: 700px;
height: 150px;
background-color: #000;
}
.clearfix:after {
content: "";
display: block;
height: 0;
visibility: hidden;
clear: both;
}
.clearfix {
*zoom: 1; /* 兼容IE6、7 | ie6,7专门清除浮动的样式 */
}
</style>
<div class="father clearfix">
<div class="son"></div>
</div>
<div class="another"></div>

父级双伪元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<style>
.son {
float: left;
weight: 100px;
height: 100px;
background-color: #0f0;
}
.another {
width: 700px;
height: 150px;
background-color: #000;
}
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1; /* 兼容IE6、7 | ie6,7专门清除浮动的样式 */
}
</style>
<div class="father clearfix">
<div class="son"></div>
</div>
<div class="another"></div>
清除浮动的方式 优点 缺点
额外标签法(隔墙法) 通俗易懂,书写方便 添加许多无意义的标签,结构化较差
父级overflow: hidden; 书写简单 溢出隐藏
父级after伪元素 结构语义化正确 由于IE6-7不支持:after,兼容性问题
父级双伪元素 结构语义化正确 由于IE6-7不支持:after,兼容性问题