早期常用空 `
` 清除浮動,破壞 HTML 語意。現代標準採用偽元素:after 配合 clear:both,零額外標籤、全瀏覽器相容。
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { zoom: 1; } /* IE6/7 觸發 hasLayout */
淘寶、3lian 等大型站點長期採用此寫法。
.clearfix:after {
content: "\20"; /* 零寬空格 U+200B,或用 "\0020" 空格 */
display: block;
height: 0;
clear: both;
}
.clearfix { zoom: 1; }
content: "\20" 插入不可見空白字元,無需 visibility:hidden,碼更少。
.clearfix::after {
content: "";
display: table;
clear: both;
}
display: table 建立新 BFC(區塊格式化上下文),自動包含浮動子元素,無需高度與可見字元。
.container { display: flow-root; }
| 專案需求 | 推薦寫法 |
|---|---|
| 需支援 IE6-8 | 經典 clearfix(含 zoom:1) |
| 支援 IE9+ / 現代瀏覽器 | 精簡 display:table 版 |
| 僅現代瀏覽器(無 IE) | display: flow-root 最語意化 |
| 元件庫/設計系統 | 提供 .clearfix、.flow-root 兩組 utility class |
採用 clearfix 偽元素方案,兼顧語意純粹、相容性與維護性,是清除浮動的專業標準寫法。