CSS:清除浮动的方法

CSS 浮动

浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。

浮动属性的本意是:让文字像流水一样环绕浮动元素

特点

包裹性

对于父元素而言,通常宽度默认为100%,高度适应内容,而对父元素使用float之后,父元素的宽度也会自适应内容,将内容包裹起来。

float
float-2

对应的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.div1 {
background:#000080;
border:1px solid red;
float: left;
}
.left {
width:200px;
height:200px;
background:#DDD;
}
</style>
</head>
<body>
<div class="div1">
<div class="left">Left</div>
</div>
</body>
</html>

高度塌陷

使用float属性之后,浮动元素脱离文档的普通流,他的父级元素无法获得浮动元素的高度,因而错误的认为里面没有元素,因而出现高度塌陷问题。

height collapse

对应代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.div1 {
background:#000080;
border:1px solid red;
}
.left {
width:200px;
height:200px;
background:#DDD;
float:left;
}
</style>
</head>
<body>
<div class="div1">
<div class="left">Left</div>
</div>
</body>
</html>

清除浮动

为了避免高度塌陷的问题,可以通过多种方式清除浮动

一、父元素固定height

既然是父元素高度塌陷,那么最简单直接的方式是将父元素的高度固定下来。但这种方式缺乏灵活性,适合固定高度的布局。

二、空标签+clear:both

在父级元素里面添加一个空的div标签,并设置div标签的clear属性为both。该方法的浏览器支持性较好,但是当浮动布局元素较多时,需要很多空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
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.div1 {
background:#000080;
border:1px solid red;
}
.left {
width:200px;
height:200px;
background:#DDD;
float:left;
}
.clearfloat{clear:both} /* new */
</style>
</head>
<body>
<div class="div1">
<div class="left">Left</div>
</div>
<div class="clearfloat"></div> <!--new-->
</body>
</html>

效果:

clear both

三、父级元素添加overflow

直接为父级元素添加属性overflow,设置值为hidden或auto即可。

  • hidden:缺点是无法和position一起使用,超出的部分会被隐藏掉。
  • auto: 缺点是当子元素高度大于父元素时,会出现滚动条。

四、定义伪类

  • 兼容性:IE8以上才支持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
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.div1 {
background:#000080;
border:1px solid red;
}
.left {
width:200px;
height:200px;
background:#DDD;
float:left;
}
/* solution */
.clearfloat:after{
display:block;
clear:both;
content:"";
visibility:hidden;
height:0
}
.clearfloat{zoom:1}
</style>
</head>
<body>
<div class="div1 clearfloat">
<div class="left">Left</div>
</div>
</body>
</html>