浮動元素脫離文檔流,導致父容器高度塌陷(高度為 0)。閉合浮動的本質是觸發父容器建立 BFC (Block Formatting Context)。本文系統梳理 6 大方案原理、優劣與適用場景。
| 標準瀏覽器 (BFC) | IE6/7 (HasLayout) |
|---|---|
| float: left/right | float: left/right |
| position: absolute/fixed | position: absolute/fixed |
| display: inline-block / table-cell / table-caption / flex / grid | display: inline-block |
| overflow: hidden/auto/scroll (≠ visible) | overflow: hidden/auto/scroll (IE7+) |
| contain: layout/paint/size | zoom: 1 (IE 專屬) |
| column-count/column-width | width/height (非 auto) |
| min/max-width/height | min/max-width/height (IE7+) |
觸發任意一條 → 父容器自動包裹浮動子元素 → 高度不再塌陷。
<div class="parent">
<div class="float-left">...</div>
<div class="float-right">...</div>
<br style="clear: both" /> <!-- 或 <div class="clear"></div> -->
</div>
❌ 污染 HTML、語意零、維護麻煩
.clearfix::after {
content: "";
display: table; /* 或 block */
clear: both;
}
.clearfix { *zoom: 1; } /* IE6/7 觸發 HasLayout */
✅ HTML 乾淨、兼容性極佳
⚠️ 需記住代碼片段、偽元素可能干擾 `:last-child` 選擇器
.parent { overflow: hidden; } /* 或 auto/scroll */
* html .parent { zoom: 1; } /* IE6 觸發 HasLayout */
✅ 一行代碼、無額外 DOM
⚠️ 可能剪切 `box-shadow`/`outline`/定位溢出內容、觸發滾動條
.parent { float: left; width: 100%; }
✅ IE/標準雙兼容(不同原理同效果)
❌ 父容器自身浮動,破壞外層佈局、需額外清除
.parent { display: flow-root; }
✅ 專為閉合浮動設計、無副作用、語意明確
✅ Chrome 58+、Firefox 53+、Safari 11+、Edge 79+
⚠️ IE/舊 Edge 不支援,需 `@supports` 降級
.parent { display: flex; } /* 或 grid */
/* 直接成為 BFC 根,浮動子元素自動包裹,且獲得強大佈局能力 */
✅ 一勞永逸、現代佈局標準
⚠️ 改變子元素佈局模式(浮動失效),需整體重構
| 場景 | 首選方案 | 降級方案 |
|---|---|---|
| 現代項目(無 IE) | `display: flow-root` | `overflow: hidden` |
| 現代項目(佈局重構中) | `display: flex/grid` | `flow-root` |
| 需兼容 IE9+ | `.clearfix` 偽元素 | `overflow: hidden` |
| 需兼容 IE6/7 | `.clearfix` + `*zoom:1` | `overflow: hidden` + `*zoom:1` |
| 組件庫/通用工具類 | `.clearfix` (最通用) | `overflow: hidden` |