CSS中clear:both的理解

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

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

参数:  
none : 容许两边均可以有浮动对象    
both : 不容许有浮动对象    
left : 不容许左边有浮动对象    
right : 不容许右边有浮动对象测试

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

好比:  
.net

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列文字就会和第一、2列文字在一块儿 ,以下图:设计

image

因此咱们在第3个这列加一个清除浮动 clear:both;  
code

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下效果正是咱们所要:蓝色块内部有红色和黄色两个色块内容,同时在蓝色块如下是第三段文本。get

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 }
相关文章
相关标签/搜索