CSS清除浮動的方法

  CSS清除浮動的方法有哪些呢?常常性地會使用到float,不少邪門的事兒都有多是浮動在做怪,清除浮動是必需要作的,並且隨時性地對父級元素清除浮動的作法也被認爲是書寫CSS的良好習慣之一。
下面看今天的教程,此爲未清除浮動源代碼,運行代碼沒法查看到父級元素淺黃色背景。css

<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>瀏覽器

 

 

1、使用空標籤清除浮動對象

  我用了好久的一種方法,空標籤能夠是div標籤,也能夠是P標籤。我習慣用<div>,夠簡短,也有不少人用<hr>,只是須要另外爲其清除邊框,但理論上能夠是任何標籤。這種方式是在須要清除浮動的父級元素內部的全部浮動元素後添加這樣一個標籤清楚浮動,併爲其定義CSS代碼:clear:both。此方法的弊端在於增長了無心義的結構元素。
<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>
    <div class=」clr」></div>
</div>教程

2、使用overflow屬性utf-8

  此方法有效地解決了經過空標籤元素清除浮動而不得不增長無心代碼的弊端。使用該方法是隻需在須要清除浮動的元素中定義CSS屬性:overflow:auto,便可!」zoom:1″用於兼容IE6。get

<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>it

3、使用after僞對象清楚浮動class

  該方法只適用於非IE瀏覽器。具體寫法可參照如下示例。使用中需注意如下幾點。1、該方法中必須爲須要清除浮動元素的僞對象中設置height:0,不然該元素會比實際高出若干像素;2、content屬性是必須的,但其值能夠爲空,藍色理想討論該方法的時候content屬性的值設爲」.」,但我發現爲空亦是能夠的。float

<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」>
    方法

相關文章
相關標籤/搜索