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; }

如上圖所示,是讓1、2、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)。
<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,
然后為偽元素加入空內容,以便偽元素中不會有內容顯示在頁面中,所以, content:"";
其次,為使偽元素不影響頁面布局,將偽元素高度設置為0,所以, height:0,
最后,要清除浮動,所以,clear:both。
tips:
content 屬性與 :before 及 :after 偽元素配合使用,來插入生成內容。