CSS清除浮動常用方法小結 CSS clear both {overflow:auto;zoom:1;}

來源:互聯網
上載者:User
常用的清除浮動的方法有以下三種:

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


<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><p id=”layout”><p id=”left”>Left</p><p id=”right”>Right</p></p>

三種清除浮動方法如下:

1、使用空標籤清除浮動。我用了很久的一種方法,空標籤可以是p標籤,也可以是P標籤。我習慣用<P>,夠簡短,也有很多人用<hr>,只是需要另外 為其清除邊框,但理論上可以是任何標籤。這種方式是在需要清除浮動的父級元素內部的所有浮動元素後添加這樣一個標籤清除浮動,並為其定義CSS代 碼:clear:both。此方法的弊端在於增加了無意義的結構元素。

對於使用額外標籤清除浮動(閉合浮動元素),是W3C推薦的 做法。至於使用<br />元素還是空<p></p>可以根據自己的喜好來選(當然你也可以使用其它區塊層級元素)。不過要注意的 是,<br />本身是有表現的,它會多出一個換行出來,所以要設定它的heigh為0,以隱藏它的表現。所以大多數情況下使用空<p>比較合 適。


<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><p id=”layout”><p id=”left”>Left</p><p id=”right”>Right</p><p class=”clr”> </p></p>

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

不過使用overflow的時候,可能會對頁面表現帶來影響,而且這種影響是不確定的,你最好是能在多個瀏覽器上測試你的頁面;


<style type=”text/css”><!–*{margin:0;padding:0;}body{font:36px bold; color:#F00; text-align:center;}#layout{background:#FF9;overflow:auto;zoom:1; }/* overflow:auto可以換成overflow:hidden,zoom:1可以換成width:100%*/#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><p id=”layout”><p id=”left”>Left</p><p id=”right”>Right</p></p>

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


<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><p id=”layout”><p id=”left”>Left</p><p id=”right”>Right</p></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.