CSS清除浮動的方法

轉自:http://www.cnblogs.com/qiye2016/p/5868217.html#undefinedhtml

一直在找這種清除浮動的方法,日常用的最多的就是clear:both;  可是總以爲不舒服,總感受這東西不屬於CSS,O(∩_∩)O哈哈~,我的感受啦。 因此想找其餘的方法,來解決浮動性問題~  讓代碼看起來更舒服,要是在一個block開始前,就來一句clear:both;chrome

總感受不爽==,這是來自柒葉的文章,以爲有這幾種方法夠用了~  分享下~瀏覽器

第一種:添加新的元素,應用clear:bothspa

HTMLcode

複製代碼
<div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <div class="clear"></div>
</div>
複製代碼

CSShtm

.clear{clear:both; height: 0; line-height: 0; font-size: 0}

 

第二種:給父級元素定義overflowblog

HTML文檔

複製代碼
<div class="outer over-flow"> //這裏添加了一個class
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <!--<div class="clear"></div>-->
</div>
複製代碼

CSSit

.over-flow{
    overflow: auto; //也能夠設置hidden
    zoom: 1; //zoom: 1; 處理兼容性問題
}

 

第三種::after 方法:(注意:做用於浮動元素的父親)class

先說原理:

這種方法清除浮動是如今網上最拉風的一種清除浮動,他是利用:after和:before來在元素內部插入兩個元素塊,從面達到清除浮動的效果。其實現原理相似於clear:both方法,只是區別在於:clear在html插入一個div.clear標籤,而outer利用其僞類clear:after在元素內部增長一個相似於div.clear的效果。下面來看看其具體的使用方法:

HTML

<div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
</div>

 

清浮動

複製代碼
.outer {zoom:1;}    /*==for IE6/7 Maxthon2==*/
.outer :after {
    clear:both;
    content:'.';
    display:block;
    width: 0;
    height: 0;
    visibility:hidden;
}   /*==for FF/chrome/opera/IE8==*/
   
複製代碼

其中clear:both;指清除全部浮動;content: '.'; display:block;對於FF/chrome/opera/IE8不能缺乏,其中content()能夠取值也能夠爲空。visibility:hidden;的做用是容許瀏覽器渲染它,可是不顯示出來,這樣才能實現清楚浮動。

下一標籤直接清浮動兄弟標籤浮動時,在下一標籤的屬性中直接寫入清除clear:both;這樣就能夠清除以上標籤的浮動而不用加入空標籤來清除浮動。

*當一個內層元素是浮動的時候,若是沒有關閉浮動時,其父元素也就不會再包含這個浮動的內層元素,由於此時浮動元素已經脫離了文檔流。也就是爲何外層不能被撐開了!

相關文章
相關標籤/搜索