清除浮動是 CSS 佈局必修課。本文梳理 clearfix 從 2004 年誕生至今的演進脈絡,對比 4 代寫法優劣,給出現代專案最佳實踐。
.clear { clear: both; line-height: 0; }
<div class="float-left">...</div>
<div class="float-right">...</div>
<br class="clear" /> <!-- 或 <div class="clear"></div> -->
.blank0 等類名殘留.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clearfix { display: inline-table; } /* IE/Mac */
* html .clearfix { height: 1%; } /* IE6 hasLayout */
.clearfix { display: block; } /* IE/Mac 結束隱藏 */
:after 偽元素插入塊級內容觸發父容器 BFC* html 選中 IE6、inline-table 針對 IE5/Mac、height:1% 觸發 hasLayout.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
* html .clearfix { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
:after,利用 zoom:1 觸發 hasLayout 達到同樣效果:afterzoom:1 可合併為 .clearfix { *zoom: 1; } (星號 Hack 同時匹配 IE6/7)float 不為 noneoverflow 不為 visibledisplay 為 table-cell/table-caption/inline-blockposition 為 absolute/fixedfloat/position 改變佈局結構 → 不適合overflow: hidden/auto 會切斷下拉選單/溢出內容 → 不適合導航選單場景display: inline-block 產生字間距 → 不適合display: table → 匿名盒子中 table-cell 形成 BFC,完美包含浮動且不影響子元素定位.clearfix:after {
content: "\200B"; /* Unicode Zero Width Space (ZWSP),替代 "." 縮減碼量 */
display: block;
height: 0;
clear: both;
}
.clearfix { *zoom: 1; } /* IE6/7 hasLayout */
content: "\200B":零寬空格,不可見、不佔寬、不觸發字體渲染visibility:hidden、font-size:0 簡化代碼.clearfix:before,
.clearfix:after {
content: "";
display: table; /* 建立 BFC,:before 防止 margin collapsing 塌陷 */
}
.clearfix:after {
clear: both; /* 核心清除浮動 */
}
.clearfix {
*zoom: 1; /* IE6/7 */
}
:before 解決**外邊距合併**問題 (父子 margin-top 塌陷)display: table 比 block 更穩健,不產生額外空白| 專案類型 | 推薦版本 | 理由 |
|---|---|---|
| 現代專案 (IE10+ / Evergreen) | 終極版二 (Micro Clearfix) | 標準化、解決 margin collapsing、體積極小 |
| 需支援 IE8-9 | 終極版二 | 完整相容 |
| 需支援 IE6/7 (維舊) | 終極版一或二 + *zoom:1 | 觸發 hasLayout |
| 極致壓碼 (Code Golf) | 終極版一 | 少 1 行偽元素 |
| 不想用 clearfix | 父容器 overflow: hidden / display: flow-root (現代) | 語義更清晰,但注意 overflow 副作用 |
clearfix 本質 = 觸發父容器建立 BFC (Block Formatting Context)。理解 BFC,就能靈活選擇 overflow、display:flow-root、flex/grid 容器等現代替代方案,而非機械複製代碼片段。