天天看點

CSS中清除浮動的方式

什麼是浮動?

使元素脫離文檔流(标準流),按照指定方式發生移動,遇到父級邊界或者相鄰的浮動元素就停下來的一種現象。

float:left|right|inherit|initial|none;

下面看一個例子:

<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>浮動</title>
	
	<style type="text/css"> 
		
		#box{
			width:400px;
			border:1px solid blue;
		}
		
		.float{
			width:100px;			
			height:100px;
		    float:left;
		}
		
		#box1{
			background-color:red;			
		}
		#box2{
			background-color:green;		  
		}
		
		#box3{
			background-color:yellow;
		}
	</style>
	
</head>

<body>
	<div id="box">
		<div id="box1" class="float">div1</div>
		<div id="box2" class="float">div2</div>
		<div id="box3" class="float">div3</div>
	</div>
</body>
</html>
           

效果圖:

CSS中清除浮動的方式

從上面現象,div1、div2、div3因設定了float:left;向左浮動了,但是最外層的div卻沒有被撐開,顯示成了一條線,也就是最外層的div高度塌陷了。那什麼情況一般會出現高度塌陷呢?

一般使父元素沒有設定高度,而子元素都設定了浮動,此時父元素就會發生高度塌陷。

那麼怎樣去解決高度塌陷的問題呢?下面就總結幾種清除浮動的方法。

1、給父級設定适當的高度

#box{
	width:400px;
	height:100px;
	border:1px solid blue;
}
           

效果圖:

CSS中清除浮動的方式

此方法隻适合高度固定的布局。

2、結尾處加空div标簽clear:both

html:

<div id="box">
	<div id="box1" class="float">div1</div>
	<div id="box2" class="float">div2</div>
	<div id="box3" class="float">div3</div>
	<div class="clear"></div>
</div>
           

css:

#box {
	width:400px;
	border:1px solid blue;
}
.float {
	width:100px;
	height:100px;
	float:left;
}
#box1 {
	background-color:red;
}
#box2 {
	background-color:green;
}
#box3 {
	background-color:yellow;
}
.clear {
	clear:both;
}
           

clear:left | right | both | none | inherit:元素的某個方向上不能有浮動元素 

clear:both:在左右兩側均不允許浮動元素。

3、父級div定義overflow:hidden

#box {
	width:400px;
	border:1px solid blue;
	overflow:hidden;
	zoom:1; //相容IE6 IE7
}
           

4、使用after僞類清除浮動(主流,推薦使用)

html:

<div id="box" class="clearfix">
	<div id="box1" class="float">div1</div>
	<div id="box2" class="float">div2</div>
	<div id="box3" class="float">div3</div>
</div>
           

css:

.clearfix:after {
	content:".";
	clear:both;
	display:block;
	height:0;
	overflow:hidden;
	visibility:hidden;
	;
}
.clearfix {
	*zoom:1; /* IE/7/6*/
}
           

此種方法的寫法很固定,一般可以寫在一個公共的地方。

.clear:after{content:'';display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}
.clear{zoom:1;}
           

對于不同清除浮動的方式,一般具體問題具體解決,以上隻是介紹了幾種主流以及相容性比較好的方式。

好文推薦:http://www.cnblogs.com/zhongweizhu/p/6003537.html

http://www.cnblogs.com/AnotherLife/p/5800751.html