當容器內所有子元素皆為浮動(float:left/right)時,父容器高度塌陷為 0,導致背景、邊框、後續版面錯亂。必須「閉合浮動」恢復父容器高度。
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .clearfix { height: 1%; } /* IE6 hasLayout */
*+html .clearfix { height: 1%; } /* IE7 hasLayout */
.clearfix { display: inline-block; } /* IE6/7 inline-block 觸發 hasLayout */
.clearfix { display: block; } /* 重置為區塊 */
原理: 利用 :after 偽元素插入不可見區塊並 clear:both;IE6/7 不支援偽元素,透過 hasLayout 機制(height:1% 或 display:inline-block)達到同樣效果。
.clearfix::after {
content: "";
display: table;
clear: both;
}
無需 hasLayout hack,代碼極精簡,現代專案首選。
.container { overflow: hidden; } /* 或 auto */
觸發 BFC(區塊格式化上下文),自動包含浮動子元素。缺點: 若容器內有 position:absolute 或負邊距元素超出邊界會被裁切;需謹慎評估。
<div class="clear"></div> /* .clear { clear:both; height:0; overflow:hidden; } */
語義不佳、污染 HTML 結構,僅作為歷史參考。
.clearfix::after { content:""; display:table; clear:both; }。overflow:hidden 最省事。