CSS clear 属性用于清除元素的浮动。clear属性指定元素是紧挨着它前面的浮动元素,还是移动到浮动元素的下方(元素被清除了浮动)。
clear属性通常和float属性一起使用。float属性指定一个元素左浮动或右浮动。而clear属性则用于指定元素的左侧、右侧,还是两侧都不允许出现浮动。
clear属性既可以用于浮动元素,也可以用于非浮动元素。clear属性只会对元素本身产生作用,对其它元素不会有任何影响。
当clear属性用于浮动元素时,它将元素的外边界移动到相关的浮动元素外边界的下方。这会影响后面浮动元素的布局,后面的浮动元素的位置无法高于它之前的元素。
例如下图中,ABC三个元素都左浮动,它们会排列为一排,如左边图像所示。如果我们将第二个元素的左浮动清除,第二个元素就会被移动到第一个元素的下方。注意第三个浮动元素,它的位置也会被改变。

如果一个容器中只有一个子元素,而这个子元素被设置了浮动,容器本身没有设置浮动,并且没有设置高度的时候,容器就会“坍塌”,如果下图A图所示。
<div class="box">
<img src="1.jpg" class="thumb">
</div>
/* css样式 */
.box{
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
img.thumb{
width: 270px;
float: left;
}

解决的方法有2个:1、使父容器也浮动起来。
.box{
float: left;
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
2、添加一个额外的空块级元素,为这个元素设置清除浮动属性,使它“撑开”容器。
<div class="box">
<img src="1.jpg" class="thumb">
<div class="clear"></div>
</div>
/* css样式 */
.box{
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
img.thumb{
width: 270px;
float: left;
}
.clear: both;
如果不想添加额外的元素,可以直接使用.box元素的:after伪元素来充当“撑开”容器的角色。
.box:after{
content: ' ';
display: block;
clear: both;
}
官方语法
clear: none | left | right | both | inherit
参数:
- none:默认值,允许元素左右两侧出现浮动。
- left:清除元素左侧的浮动,元素被向下移动。
- right:清除元素右侧的浮动,元素被向下移动。
- both:清除元素左右两侧的浮动,元素被向下移动。
- inherit:继承父元素的clear值。
clear属性的初始值为none。
应用范围
clear属性可以应用在所有块级元素上。
示例代码
下面是一个清除浮动的经典代码,详细代码介绍可以参考:Micro clearfix hack。这段代码兼容Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+浏览器。代码如下:
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.cf {
*zoom: 1;
}
在线演示
DEMO1:下面的例子演示了元素清除浮动之前和清除浮动之后的情况。
没有清除浮动:
清除浮动之后:
浏览器支持
所有的现代浏览器都支持clear属性,包括Chrome,Firefox,Safari,Opera,IE 以及 Android 和 iOS。