清除浮動float (:after方法)

1. 何時須要清除浮動?清除浮動有哪些方法?
(1)對元素進行了浮動(float)後,該元素就會脫離文檔流,浮動在文檔之上。在CSS中,任何元素均可以浮動。浮動元素會生成一個塊級框,而不論它自己是何種元素。
float主要流行與頁面佈局,而後在使用後沒有清除浮動,就會後患無窮。
先看實例:
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;}
.div1{ width:80px; height:80px; background:#f00; float:left; }
.div2{ width:80px; height:80px; background:blue; float:left; }
.div3{ width:80px; height:80px; background:sienna; float:left; }

 如上圖所示,是讓一、二、3這三個元素產生浮動所形成的現象。
下面看一下,若是這三個元素不產生浮動,會是什麼樣子?
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;}
.div1{ width:80px; height:80px; background:#f00; /*float:left;*/ }
.div2{ width:80px; height:80px; background:blue;/* float:left; */}
.div3{ width:80px; height:80px; background:sienna;/* float:left;*/ }
如上圖所示,當內層的1/2/3元素不浮動,則外層元素的高是會被自動撐開的。
因此當內層元素浮動的時候,就出現如下影響:
背景不能顯示;邊框不能撐開;margin設置值不能正確顯示。
(2)清除浮動
方法一:添加新的元素,應用 clear:both;
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="clear"></div>
</div>
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;}
.div1{ width:80px; height:80px; background:#f00; float:left; }
.div2{ width:80px; height:80px; background:blue; float:left; }
.div3{ width:80px; height:80px; background:sienna; float:left; }
.clear{ clear:both; height:0; line-height:0; font-size:0; }

方法二:父級div定義 overflow:auto;(主意:是父級div,也就是這裏的 div.outer)html

<div class="outer over-flow">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
 
.outer{ border:1px solid #ccc; background:#fc9; color:#fff; margin:50px auto; padding:50px;}
.div1{ width:80px; height:80px; background:#f00; float:left; }
.div2{ width:80px; height:80px; background:blue; float:left; }
.div3{ width:80px; height:80px; background:sienna; float:left; }
.over-flow{ overflow:auto; zoom:1;  } //zoom:1;是在處理兼容性問題

原理:使用overflow屬性來清除浮動有一點須要注意,overflow屬性共有三個屬性值:hidden,auto,visible。咱們能夠使用hidden和auto值來清除浮動,但切記不能使用visible值,若是使用這個值,將沒法達到 清除浮動效果,其餘兩個值均可以。
overflow 屬性規定當內容溢出元素框時發生的事情。
方法三:聽說最高大上的方法,:after方法。(注意:做用於浮動元素的父親)
 原理:利用:after和:before來在元素內部插入兩個元素塊,從而達到清除浮動的效果。其實現原理相似於clear:both方法,只是區別在於:clear在html中插入一個div.clear標籤,而outer利用其僞類clear:after在元素內部增長一個相似於div.clear的效果。
.outer { zoom:1; } //爲了兼容性,由於ie6/7不能使用僞類,因此加上此行代碼。
.outer:after { clear:both;content:'';display:block;width:0;height:0;visibility:hidden; }
 

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

利用僞元素,就能夠再也不HTML中加入標籤。瀏覽器

:after 的意思是再.outer內部的最後加入爲元素:after,
佈局

首先要顯示僞元素,因此display:block,spa

而後爲僞元素加入空內容,以便僞元素中不會有內容顯示在頁面中,因此, content:"";code

其次,爲使僞元素不影響頁面佈局,將僞元素高度設置爲0,因此, height:0,htm

最後,要清除浮動,因此,clear:both。
blog

tips:
content 屬性與 :before 及 :after 僞元素配合使用,來插入生成內容。
相關文章
相關標籤/搜索