巧用clear:both 清楚上層float的影響

我們在製作網頁中用div+css或者稱xhtml+css都會遇到一些很詭異的情況,明明佈局正確,但是整個畫面卻混亂起來了,有時候在IE6下看的很正常的,到ie7或者火狐下看時,就一片混亂了,無論怎麼計算,就是不能將排版改正過來。其實,這一切都是浮動搞得鬼,也就是css中的float,要解決情況,就需要使用clear:both了。

CSS手冊上是這樣說明的:該屬性的值指出了不允許有浮動對象的邊。這個屬性是用來控制float屬性在文檔流的物理位置的。

當屬性設置float(浮動)時,其所在的物理位置已經脫離文檔流了,但是大多時候我們希望文檔流能識別float(浮動),或者是希望float(浮動)後面的元素不被float(浮動)所影響,這個時候我們就需要用clear:both;來清除。

 

程序代碼:

<p style="float:left;width:200px;">這個是第1列,</p>
<p style="float:left;width:400px;">這個是第2列,</p>
<p>這個是第3列。</p>

如果不用清除浮動,那麼第3列文字就會和第1、2列文字在一起 ,所以我們在第3個這列加一個清除浮動 clear:both;

通常,我們往往會將“清除浮動”單獨定義一個CSS樣式,如:

程序代碼

.clear {
     clear: both;
}



然後使用<div class="clear"></div>來專門進行“清除浮動”。
不過也有不贊同意見是,<div class="clear"></div>可以不寫,直接在下層清除就可以了。
比如本來好好的

程序代碼

<p style="float:left;width:200px;">這個是第1列,</p>
<p style="float:left;width:400px;">這個是第2列,</p>
<p style="clear:both;">這個是第3列。</p>



非要整成

程序代碼

<p style="float:left;width:200px;">這個是第1列,</p>
<p style="float:left;width:400px;">這個是第2列,</p>
<div class="clear"></div>
<p>這個是第3列。</p>

這點看來,<div class="clear"></div>確實不需要寫。
不過很顯然,我們在網頁設計時還有一種很普遍的情況:
程序代碼

<style type="text/css">
#main {background-color: #3399CC;width: 600px;padding: 20px;}
#sidebar {background-color: #FF6600;     float: left;width: 130px;}
#container {float: right;width: 420px;background-color: #FFFF33;}
</style>
<div id="main">
<div id="sidebar">第一段內容 第一段內容 第一段內容</div>
<div id="container">第二段內容 第二段內容 第二段內容</div>
</div>
<p style="clear:both;">第三段內容</p>

該頁面測試在IE下效果正合所要:藍色塊內部有紅色和黃色兩個色塊內容,同時在藍色塊以下是第三段文本。

不過FF的效果可不是這樣的。我們不能單單想在下一層清除就能完成我們的工作,我們必須在浮動元素所在標籤閉合之前及時進行“清除”。
程序代碼

<style type="text/css">
#main {background-color: #3399CC;width: 600px;padding: 20px;}
#sidebar {background-color: #FF6600;     float: left;width: 130px;}
#container {float: right;width: 420px;background-color: #FFFF33;}
.clear {clear: both;}
</style>
<div id="main">
<div id="sidebar">第一段內容 第一段內容 第一段內容</div>
<div id="container">第二段內容 第二段內容 第二段內容</div>
<div class="clear"></div>
</div>
<p>第三段內容</p>

對於因多加的<div class="clear"></div>標籤會引起IE和FF高度變化,通過如下方法解決:
程序代碼

clear {
     clear: both;
     height:1px;
     margin-top:-1px;
     overflow:hidden;
}

 

程序代碼

<style type="text/css">
#main {background-color: #3399CC;width: 600px;padding: 20px;}
#sidebar {background-color: #FF6600;     float: left;width: 130px;}
#container {float: right;width: 420px;background-color: #FFFF33;}
.clear {clear: both;height:1px;margin-top:-1px;overflow:hidden;}
</style>
<div id="main">
<div id="sidebar">第一段內容 第一段內容 第一段內容</div>
<div id="container">第二段內容 第二段內容 第二段內容</div>
<div class="clear"></div>
</div>
<p>第三段內容</p>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章