子元素 div 高度不固定(如浮動、絕對定位、內容動態生成),父 div 高度塌陷為 0,無法包裹子元素。
#parent {
overflow: hidden; /* 或 auto */
/* 注意:會切掉陰影、absolute 溢出內容 */
}
.clearfix::after {
content: "";
display: block;
clear: both;
}
.clearfix { *zoom: 1; } /* IE6/7 觸發 hasLayout */
HTML:<div id="parent" class="clearfix">...</div>
<div id="parent">
<div id="child">...</div>
<div style="clear:both;"></div> <!-- 或 <br style="clear:both;" /> -->
</div>
缺點:增加無語意標籤。
#parent { float: left; width: 100%; }
會導致父層脫離文件流,影響後續版面,不建議。
#parent { display: flex; } /* 或 grid */
/* 子元素自動撐開父層高度,無需清除浮動 */
<div id="main" style="border:1px solid #999; background:#ccc; overflow:hidden;">
<div id="content" style="float:left;">
<p>demo1</p><p>demo2</p><p>demo3</p>
</div>
</div>
| 場景 | 推薦方案 |
|---|---|
| 現代專案(IE10+) | Flexbox / Grid |
| 需支援 IE8+ | Clearfix 偽元素 |
| 無陰影/溢出內容 | overflow: hidden |
| 快速原型/舊專案維護 | 額外 <br clear="all"> |