CSS中clear:both的理解

那年仲夏 提交于 2019-12-04 17:12:06

在CSS中我们会经常要用到“清除浮动”Clear,比较典型的就是clear:both;    
CSS手册上是这样说明的:该属性的值指出了不允许有浮动对象的边。这个属性是用来控制float属性在文档流的物理位置的。    
   
当属性设置float(浮动)时,其所在的物理位置已经脱离文档流了,但是大多时候我们希望文档流能识别float(浮动),或者是希望float(浮动)后面的元素不被float(浮动)所影响,这个时候我们就需要用clear:both;来清除。

语法: clear : none | left |right | both

参数:  
none : 允许两边都可以有浮动对象    
both : 不允许有浮动对象    
left : 不允许左边有浮动对象    
right : 不允许右边有浮动对象

说明: 该属性的值指出了不允许有浮动对象的边。请参阅float属性。 对应的脚本特性为clear

比如:  

1 1 <p style="float:left;width:200px;">this is 1st row</p>2 2 <p style="float:right;width:400px;">this is 2ed row</p>3 3 <p >this is the third row</p>


如果不用清除浮动,那么第3列文字就会和第1、2列文字在一起 ,如下图:

image

所以我们在第3个这列加一个清除浮动 clear:both;  

1 <p style="float:left;width:200px;">this is 1st row</p>2 <p style="float:right;width:400px;">this is 2ed row</p>3 <p style="clear:left;">this is the third row</p>

这时的效果如下:

image

我们在网页设计时还有一种很普遍的情况:

 1 <style type="text/css"> 2 #main {background-color: #3399CC;width: 600px;padding: 20px;} 3 #sidebar {background-color: #FF6600;    float: left;width: 130px;} 4 #container {float: right;width: 420px;background-color: #FFFF33;} 5 </style> 6 <div id="main"> 7 <div id="sidebar">content1 content1 content1</div> 8 <div id="container">content2 content2 content2</div> 9 </div>10 <p style="clear:both;">content3</p>

该页面测试在IE下效果正是我们所要:蓝色块内部有红色和黄色两个色块内容,同时在蓝色块以下是第三段文本。

image  
不过Firefox的效果可不是这样的,如下所示:

image

我们不能单单想在下一层清除就能完成我们的工作,我们必须在浮动元素所在标签闭合之前及时进行“清除”。

 1 <style type="text/css"> 2 #main {background-color: #3399CC;width: 600px;padding: 20px;} 3 #sidebar {background-color: #FF6600;    float: left;width: 130px;} 4 #container {float: right;width: 420px;background-color: #FFFF33;} 5 .clear {clear: both;} 6 </style> 7 <div id="main"> 8 <div id="sidebar">content1 content1 content1</div> 9 <div id="container">content2 content2 content2</div>10 <div class="clear"></div>11 </div>12 <p>content3</p>

这时Firefox下的页面显示也就正常了

image

不过这时会因多加的<div class="clear"></div>标签会引起IE和FF高度变化(如下图,显然IE下蓝色背景的高度增加了):

image

这个高度变化可以通过如下方法解决:

1 .clear {2      clear: both;3      height:1px;4      margin-top:-1px;5      overflow:hidden;6 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!