CSS清除浮動經常使用方法小結

    使用div+css佈局的好處不用多說,常常性地會使用到float,那麼清除浮動就是必需要作的,並且隨時性地對父級元素清除浮動的作法也被認爲是書寫CSS的良好習慣之一。css

    經常使用的清除浮動的方法有如下三種。
      此爲未清除浮動源代碼,運行代碼沒法查看到父級元素淺黃色背景。
瀏覽器

<style type="text/css">  網絡

<!--  佈局

    *{margin:0;padding:0;}  spa

    body{font:36px bold; color:#F00; text-align:center;}  對象

    #layout{background:#FF9;}  it

#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}  class

    #right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}  float

-->  方法

</style>  


<div id="layout">  

    <div id="left">Left</div>  

    <div id="right">Right</div>  

</div> 

一、使用空標籤清除浮動。我用了好久的一種方法,空標籤能夠是div標籤,也能夠是P標籤。我習慣用<P>,夠簡短,也有不少人用<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>  

    <p class="clr"></p>  

</div> 

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

<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瀏覽器。具體寫法可參照如下示例。使用中需注意如下幾點。1、該方法中必須爲須要清除浮動元素的僞對象中設置height:0,不然該元素會比實際高出若干像素;2、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>  


<div id="layout">  

    <div id="left">Left</div>  

    <div id="right">Right</div>  

</div> 

此三種方法皆有必定弊端,使用時應擇優選擇,比較之下第二種方法更爲可取。以上方法,並不是原創,皆來源於網絡,在此小做整理,原做者保留全部權利。

相關文章
相關標籤/搜索