目錄css
例如:html
HTML:佈局
<div class="first"> <div class="first-child1">first-child1</div> <div class="first-child2">first-child2</div> </div> <div class="second"> second </div> <div class="third"> third </div>
CSS:網站
.first{ width: 300px; background-color: pink; } .first .first-child1,.first .first-child2{ float: left; width: 100px; height: 100px; } .first .first-child1{ background-color: purple; margin-right: 10px; } .first .first-child2{ background-color: red; } .second{ width: 200px; height: 150px; background-color: blue; } .third{ width: 100px; height: 150px; background-color: green; }
表現爲:code
由上面的例子能夠看出,first盒子沒有設置高度,由子元素撐開,可是因爲子盒子設置了浮動,脫離了標準流,因此致使first盒子沒有高度,表現爲second和third盒子向上移動了。orm
能夠得出產生高度塌陷的緣由:htm
在文檔流中,父元素的高度默認是被子元素撐開的,也就是子元素多高,父元素就多高。可是當爲子元素設置浮動之後,子元素會徹底脫離文檔流,此時將會致使子元素沒法撐起父元素的高度,致使父元素的高度塌陷。因爲父元素的高度塌陷了,則父元素下的全部元素都會向上移動,這樣將會致使頁面佈局混亂。blog
給父元素設置固定高度。可是使用這種方式後,父元素的高度就不能根據子元素自動撐高了,能夠根據本身頁面的特色,若是能夠固定高度,可使用這種方式,不然,不推薦這種方式。圖片
額外標籤法,這是w3c推薦的解決方案,可是不推薦,由於html的原則是寫出語義化的標籤,這種方式會額外增長無心義的標籤。文檔
<div class="first"> <div class="first-child1">first-child1</div> <div class="first-child2">first-child2</div> <div style="clear: both;"></div> </div>
父元素的overflow屬性(開啓元素的BFC):
.clearfix{ overflow: hidden; }
使用這種方式,屬性值能夠是非visible(hidden/auto/scroll)中任意,可是建議用hidden。
這種方式反作用較小,這種方式在ie6中不支持,能夠外加zoom: 1;
.clearfix{ overflow: hidden; zoom: 1;/*針對ie6*/ }
單僞元素after清除浮動(開啓元素的BFC):
.clearfix::after{ content: "";/*僞元素內容爲空*/ display: block;/*非默認的就行,也能夠是table等等*/ height: 0;/*僞元素高度爲0,不影響其餘元素*/ clear: both;/*清除浮動*/ visibility: hidden;/*不可見*/ } .clearfix{ zoom: 1;/*ie6元素沒有BFC模式,可是這句代碼會開啓ie6中的hasLayout模式,只在ie中支持*/ }
這種方式如今使用比較普遍,不少大網站都是使用這種方式,反作用較小,只須要在配合處理ie6就能夠了。
雙僞元素清除浮動(開啓元素的BFC):
.clearfix::before,.clearfix::after{ content: ""; display: block; clear: both; } .clearfix{ zoom: 1;/*ie6元素沒有BFC模式,可是這句代碼會開啓ie6中的hasLayout模式,只在ie中支持*/ }
這種作法寫法比較麻煩,也不推薦。
清除浮動對父元素的影響後的效果:
根據W3C的標準,在頁面中元素都一個隱含的屬性叫作Block Formatting Context,簡稱BFC,該屬性能夠設置打開或者關閉,默認是關閉的。
當開啓元素的BFC之後,元素將會具備以下的特性: