CSS中clear:both的理解

在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 }

转载于:https://my.oschina.net/u/658505/blog/152956

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值