表現
例如:
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;} |
表現為:

產生的原因
由上面的例子可以看出,first盒子沒有設置高度,由子元素撐開,但是由于子盒子設置了浮動,脫離了標準流,所以導致first盒子沒有高度,表現為second和third盒子向上移動了。
可以得出產生高度塌陷的原因:
在文檔流中,父元素的高度默認是被子元素撐開的,也就是子元素多高,父元素就多高。但是當為子元素設置浮動以后,子元素會完全脫離文檔流,此時將會導致子元素無法撐起父元素的高度,導致父元素的高度塌陷。由于父元素的高度塌陷了,則父元素下的所有元素都會向上移動,這樣將會導致頁面布局混亂。
高度塌陷的解決辦法:
1、給父元素設置固定高度。但是使用這種方式后,父元素的高度就不能根據子元素自動撐高了,可以根據自己頁面的特點,如果可以固定高度,可以使用這種方式,否則,不推薦這種方式。
2、額外標簽法,這是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> |
3、父元素的overflow屬性(開啟元素的BFC):
| .clearfix{ overflow: hidden;} |
使用這種方式,屬性值可以是非visible(hidden/auto/scroll)中任意,但是建議用hidden。
這種方式副作用較小,這種方式在ie6中不支持,可以外加zoom: 1;
| .clearfix::after{ content: "";/*偽元素內容為空*/ display: block;/*非默認的就行,也可以是table等等*/ height: 0;/*偽元素高度為0,不影響其他元素*/ clear: both;/*清除浮動*/ visibility: hidden;/*不可見*/}.clearfix{ zoom: 1;/*ie6元素沒有BFC模式,但是這句代碼會開啟ie6中的hasLayout模式,只在ie中支持*/} |