浮動元素脫離正常文檔流,不再佔據父容器空間 → 父容器高度按非浮動內容計算 → 高度塌陷為 0 (若無其他內容)。
視覺後果:背景色/邊框/邊距異常、後續元素錯位、佈局崩塌。
<div class="container">
<div class="float-left">...</div>
<div class="float-right">...</div>
<div class="clearfix"></div> <!-- 汙染 HTML -->
</div>
.clearfix { clear: both; height: 0; overflow: hidden; }
缺點:語義汙染、維護困難、無法復用。
.container { overflow: hidden; zoom: 1; /* IE6/7 觸發 hasLayout */ }
副作用:
box-shadow、transform、position: absolute 子元素超出部分overflow: auto 可能出現滾動條text-overflow: ellipsis 多行截斷/* Nicolas Gallagher 微調版 */
.clearfix::before,
.clearfix::after {
content: "";
display: table; /* table 比 block 更穩,防止 margin collapsing */
}
.clearfix::after { clear: both; }
.clearfix { *zoom: 1; } /* IE6/7 */
原理:::after 生成塊級盒子,clear: both 強制其位於浮動元素之下 → 撐開父容器高度。
.container { float: left; width: 100%; }
連鎖反應:父級浮動 → 祖先也需浮動 → 整頁浮動 → 佈局失控。
.container { display: table; width: 100%; }
缺點:width: 100% 配合 display: table 在某些情況下佈局異常、margin: 0 auto 居中失效。
/* Flex 容器自動包含浮動子項 (float 於 flex 子項無效) */
.flex-container { display: flex; gap: 1rem; }
/* Grid 容器同理 */
.grid-container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }
/* 現代重置:直接禁用 float 佈局 */
* { float: none !important; } /* 極端但有效 */
.container { display: flow-root; }
優勢:
| 場景 | 推薦方案 | 備選方案 | 避免方案 |
|---|---|---|---|
| 現代項目 (IE 不支援) | display: flow-root | Flex/Grid 容器 | Overflow、額外標籤 |
| 需支援 IE11 | Micro Clearfix (偽元素) | overflow: hidden (無陰影/絕對定位) | 額外標籤 |
| 需支援 IE9-10 | Micro Clearfix + zoom:1 | display: table | Overflow auto |
| 組件庫/通用庫 | 提供 .clearfix 工具類 + 文檔建議 Flow-root | - | - |
| 重構舊專案 | 逐步遷移至 Flex/Grid,移除所有 float 佈局 | - | 新增 float 代碼 |
.scroll-container {
height: 300px; /* 固定高度 */
overflow: auto; /* 需要滾動 */
/* 同時需要包含浮動子元素 */
}
/* 衝突:overflow:auto 剪裁內容,但也清除浮動 */
/* 解決:內層包裹 */
.scroll-container { height: 300px; overflow: auto; }
.scroll-inner { display: flow-root; /* 或 clearfix */ }
.clearfix {
*zoom: 1; /* IE6/7 觸發 hasLayout */
_height: 1%; /* IE6 專用,觸發 hasLayout */
min-height: 1%; /* 現代瀏覽器忽略 */
overflow: visible; /* 覆蓋可能的 hidden */
}
/* ❌ 避免:Float 佈局 */
.grid { overflow: hidden; }
.item { float: left; width: 33.33%; }
/* ✅ 現代:Flex 佈局 */
.grid { display: flex; flex-wrap: wrap; gap: 1rem; }
.item { flex: 1 1 300px; } /* 自適應、無塌陷、無清除煩惱 */
/* ✅ 現代:Grid 佈局 */
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1rem; }
float 作為佈局手段 (僅用於文字環繞圖片)float 佈局遷移計劃納入技術債務清單.clearfix 工具類,文檔標註 display: flow-root 為首選"selector-no-floating": true (實驗性)清除浮動是 Float 時代的「補丁藥」,現代 CSS 佈局 (Flex/Grid/Flow-root) 從根源上消除了高度塌陷問題。理解歷史方案原理是為了維護舊代碼,新代碼應堅決擁抱現代佈局範式。