CSS清除浮動方法總匯

來源:互聯網
上載者:User
使用xhtml+css布局經常性地會使用到float,很多邪門的事兒都有可能是浮動在作怪,那麼清除浮動就是必須要做的,而且隨時性地對父級元素清除浮動的做法也被認為是書寫CSS的良好習慣之一。

此為未清除浮動原始碼,運行代碼無法查看到父級元素淺黃色背景。

<style type="text/css">body { font-size:24px; color:red; }#layout { background:#FF0; }#left { float:left; width:20%; height:200px; background:#CCC; }#right { float:right; width:30%; height:80px; background:#CCC; }</style><p id="layout"><p id="left">Left</p><p id="right">Right</p>

未清除浮動前:

三種清除浮動方法如下:

1、使用空標籤清除浮動。

我用了很久的一種方法,空標籤可以是p標籤,也可以是p/span/br等標籤,理論上可以是任何標籤。這種方式是在需要清除浮動的父級元素內部的所有浮動元素後添加這樣一個標籤清除浮動,並為其定義CSS代碼:clear:both。此方法的弊端在於增加了無意義的結構元素。

ps:<br clear=”all”/>也可以實現效果。

<style type="text/css">body { font-size:24px; color:red; }#layout { background:#FF0; }#left { float:left; width:20%; height:200px; background:#CCC; }#right { float:right; width:30%; height:80px; background:#CCC; }.clr { clear:both; }</style><p id="layout"><p id="left">Left</p><p id="right">Right</p><p style="clear:both"/></p>

2、使用overflow屬性。

此方法有效地解決了通過空標籤元素清除浮動而不得不增加無意代碼的弊端。使用該方法是只需在需要清除浮動的元素中定義CSS屬性:overflow:auto,即可!”zoom:1″用於相容IE6。

<style type="text/css">body { font-size:24px; color:red; }#layout { background:#FF0; overflow:auto; zoom:1; }#left { float:left; width:20%; height:200px; background:#CCC; }#right { float:right; width:30%; height:80px; background:#CCC; }</style></head> <body><p id="layout"><p id="left">Left</p><p id="right">Right</p>

3、使用after偽對象清除浮動。

該方法只適用於非IE瀏覽器。具體寫法可參照以下樣本。使用中需注意以下幾點。
一、該方法中必須為需要清除浮動元素的偽對象中設定height:0,否則該元素會比實際高出若干像素;
二、content屬性是必須的,但其值可以為空白,網上討論該方法的時候content屬性的值設為”.”,但我發現為空白也是可以的。

<style type="text/css">body { font-size:24px; color:red; }#layout { background:#FF0;  }#layout:after{display:block;clear:both; content:""; visibility:hidden;height:0;}#left { float:left; width:20%; height:200px; background:#CCC; }#right { float:right; width:30%; height:80px; background:#CCC; }</style><p id="layout"><p id="left">Left</p><p id="right">Right</p>

清除浮動後:

此三種方法各有利弊,使用時應擇優選擇,比較之下第二種方法更為可取。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.