應用DivCSS網頁佈局,經常性地會使用到float,很多邪門的事兒都有可能是浮動在作怪,關於清除浮動,在原來也有過很多介紹。清除浮動是必須要做的,而且隨時性地對父級元素清除浮動的做法也被認為是書寫CSS的良好習慣之一。
以下看今天的教學課程,此為未清除浮動原始碼,執行程式碼無法查看到父級元素淺黃色背景。
![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/20/6045_quote.gif)
Example Source Code
[www.downcodes.com] <style type=”text/css”>
<!–
*{margin:0;padding:0;}
body{font:36px bold; color:#F00; text-align:center;}
#layout{background:#FF9;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
<div id=”left”>Left</div>
<div id=”right”>Right</div>
</div>
未清除浮動前如圖所示:
一、使用空標籤清除浮動我用了很久的方法,空標籤可以是div標籤,也可以是P標籤。我習慣用<P>,夠短,也有很多人用<hr>,只是需要另外為其清除邊框,但理論上可以是任何標籤。這種方式是在需要清除浮動的父級元素內部的所有浮動元素後添加這樣一個標籤清楚浮動,並為其定義CSS代碼:clear:both。此方法的弊端在於增加了無意義的結構元素。
![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/20/6045_quote.gif)
Example Source Code
[www.downcodes.com] <style type=”text/css”>
<!–
*{margin:0;padding:0;}
body{font:36px bold; color:#F00; text-align:center;}
#layout{background:#FF9;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
.clr{clear:both;}
–>
</style>
<div id=”layout”>
<div id=”left”>Left</div>
<div id=”right”>Right</div>
<p class=”clr”>
</div>
二、使用overflow屬性此方法有效地解決了透過空標籤元素清除浮動而不得不增加無意程式碼的弊端。使用該方法是只需在需要清除浮動的元素中定義CSS屬性:overflow:auto,即可! ”zoom:1″用於相容IE6。
![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/20/6045_quote.gif)
Example Source Code
[www.downcodes.com] <style type=”text/css”>
<!–
*{margin:0;padding:0;}
body{font:36px bold; color:#F00; text-align:center;}
#layout{background:#FF9;overflow:auto;zoom:1;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
<div id=”left”>Left</div>
<div id=”right”>Right</div>
</div>
三、使用after偽對象清楚浮動此方法只適用於非IE瀏覽器。具體寫法可參考以下範例。使用中需注意以下幾點。一、該方法中必須為需要清除浮動元素的偽對像中設定height:0,否則該元素會比實際高出若干像素;二、content屬性是必須的,但其值可以為空,藍色理想討論該方法的時候content屬性的值設為”.”,但我發現為空亦是可以的。
![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/20/6045_quote.gif)
Example Source Code
[www.downcodes.com] <style type=”text/css”>
<!–
*{margin:0;padding:0;}
body{font:36px bold; color:#F00; text-align:center;}
#layout{background:#FF9;}
#layout:after{display:block;clear:both;content:”";visibility:hidden;height:0;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
<div id=”left”>Left</div>
<div id=”right”>Right</div>
</div>
清楚浮動後如圖所示:
此三種方法各有利弊,使用時應擇優選擇,比較之下第二種方法較為可取。