經典 Clearfix(Nicolas Gallagher 改良版)
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
.clearfix::after { clear: both; }
.clearfix { *zoom: 1; } /* IE 6/7 觸發 hasLayout */
精簡版(僅支援現代瀏覽器 + IE8+)
.clearfix::after {
content: "";
display: table;
clear: both;
}
.clearfix { *zoom: 1; }
原理解析
::before 修正 margin-top 塌陷(現代瀏覽器)。
::after + clear:both 清除浮動,撐開父層高度。
*zoom:1 觸發 IE6/7 hasLayout,達到同樣清除效果。
其他常見清除浮動方法比較
| 方法 | 優點 | 缺點 |
額外空 <div style="clear:both"></div> | 簡單直觀 | 污染 HTML 結構、無語意 |
父層 overflow:hidden/auto | 無額外標籤 | 可能裁切陰影/絕對定位子元素、觸發滾動條 |
父層 display:flow-root | 現代標準、語意清晰 | IE/Edge 舊版不支援 |
父層 float:left/right | 自動包含浮動子元素 | 父層本身脫離文件流,影響佈局 |
最佳實踐建議
- 專案統一採用
.clearfix 類別,語意明確、可複用。
- 現代專案(不支援 IE)直接用
display: flow-root。
- 避免濫用
overflow:hidden 清除浮動,防止副作用(參見 overflow 陷阱)。