clear在w3.org官方的解释
The clear property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.
盒子的边不和前面浮动盒子相邻
因为html是上下的文档流,所以这里的边指的左边和右边
clear:left/right的实际用途(一)
clear:left/right最实际也是最常见的用途就是实现垂直环绕布局。
下图所示的布局实现,HTML结构
可能会把头像div和姓名div放在同一个父级div1中,div1左浮动
自我描述div2右浮动。
这样实现倒是也可以,但是头像 姓名 自我描述按照中文意思均属同级,而此实现方式则把头像 姓名 作为子级。
哪如何将头像 姓名 自我描述作为同级,实现上面的布局呢
这个时候则要借助 clear 实现垂直环绕布局。
<div style="width:500px;height: 100px;background:cornsilk;font-size:12px;overflow:hidden;_zoom:1;">
<div style="float:left;width:100px;height: 60px;background: yellow;...">头像</div>
<div style="float:left;clear:left;width:100px;height: 40px;background: red;...">姓名</div>
<div style="margin-left:150px;width:300px;height: 100px;background: #C3D7E4;...">自我描述……</div>
</div>
不使用clear的时候,头像和姓名均左浮动,所有姓名会再头像右侧,想要姓名再头像下面,则需要clear姓名的左浮动
image.png
即
使用clear的时候
image.png
clear:left/right的实际用途(二)
由于元素浮动后脱离了文档流,所以父元素是无法根据元素来自适应的。解决此问题最常用的办法由两种,第一种就是在所有浮动元素后加:
<div style="clear:both;height:0px;"></div>
如图
使用clear的
使用clear
不使用clear
不使用clear
原来后边的Clear:both;其实就是利用清除浮动来把外层的div撑开,所以有时候,我们在将内部div都设置成浮动之后,就会发现,外层div的背景没有显示,原因就是外层的div没有撑开,太小,所以能看到的背景仅限于一条线。
第二种办法,使用万能clear:
.clearfix:after
{
visibility: hidden;
display: block;
font-size: 0;
content: ".";
clear: both;
height: 0;
}
* html .clearfix
{
zoom: 1;
}
*:first-child + html .clearfix
{
zoom: 1;
}
然后在你需要自适应的元素上加上class=” clearfix”即可。
这里边的原理:
(1)、首先是利用:after这个伪类来兼容FF、Chrome等支持标准的浏览器。
:after伪类IE不支持,它用来和content属性一起使用设置在对象后的内容,例如:
a:after{content:"(link)";}
这个CSS将会让a标签内的文本后边加上link文本文字。
(2)、利用“* html”这个只有IE6认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE6。
(3)、利用“*:first-child + html”这个只有IE7认识的选择符,设置缩放属性“zoom: 1;”实现兼容IE7。
参考
准确理解CSS clear:left/right的含义及实际用途
经验分享:CSS浮动(float,clear)通俗讲解
正确理解 clear:both
网友评论