美文网首页
clear:left/right 理解

clear:left/right 理解

作者: _海角_ | 来源:发表于2017-11-23 16:27 被阅读34次

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结构

image
可能会把头像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

相关文章

  • clear:left/right 理解

    clear在w3.org官方的解释The clear property indicates which sides...

  • 流式布局

    float:left, right, none(不允许进行流动)clear:both, right, left,n...

  • 浮动。布局

    布局属性: float:left/right/none clear:left/right/both 设置一个元素左...

  • 2018-04-04浮动布局

    Day009,30min float:left/right, clear:both

  • 11.22 前端学习

    清除浮动 clear:left清除左浮动clear:right清除右浮动clear:both清除对它影响最大的浮动...

  • 前端06

    清除浮动 clear:left清除左浮动clear:right清除右浮动clear:both清除对它影响最大的浮动...

  • 06 前端学习

    清除浮动 clear:left清除左浮动clear:right清除右浮动clear:both清除对它影响最大的浮动...

  • CSS网站布局实录笔记-Part2

    1. 浮动式布局 float: left, right 清理:clear:left, both 何时选用浮动定位:...

  • CSS 常用属性

    布局 position,z-index top, bottom, right, left float, clear...

  • 关于Clear:both,left,right

    清除浮动是一个很常见的东西。得了解下,不能就记个形式,这样对自己不负责呀。问题的描述,前端写代码稍不留神,就会这个...

网友评论

      本文标题:clear:left/right 理解

      本文链接:https://www.haomeiwen.com/subject/lyuzvxtx.html