浮動元素**脫離正常文檔流**,父容器高度塌陷為 0,導致:
| 方案 | 代碼 | 原理 | 優點 | 缺點 | 推薦度 |
|---|---|---|---|---|---|
1. 空標簽 <div class="clear"> | .clear{clear:both} | clear 阻止浮動影響 | 兼容最好 | **污染 HTML 語義**、結構耦合 | ❌ 棄用 |
2. 父級 overflow: hidden/auto | .parent{overflow:hidden} | 觸發 BFC | 零額外標簽 | 剪切陰影/絕對定位溢出、滾動條風險 | ⚠️ 謹慎 |
3. 父級 display: flow-root | .parent{display:flow-root} | 現代 BFC 觸發 | 語義純淨、無副作用、IE 不支持 | IE11 需降級 | ✅ **現代首選** |
4. 偽元素 ::after (Clearfix) | 見下文標準寫法 | 偽元素 clear + BFC | 語義純淨、IE8+ 全支持、無視覺副作用 | 需額外 CSS 規則 | ✅ **通用首選** |
5. 父級 flex/grid | .parent{display:flex} | 新格式化上下文 | 順便解決佈局、居中、對齊 | 改變子元素佈局行為 | ✅ **新項目首選** |
.clearfix::after {
content: "";
display: table; /* 或 block */
clear: both;
}
.clearfix { *zoom: 1; } /* IE6/7 hasLayout */
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
.clearfix::after { clear: both; }
.clearfix { *zoom: 1; }
::before 解決頂部 margin 塌陷 (margin collapsing)。
.clearfix::after {
content: "";
display: block;
clear: both;
}
float 不為 noneposition 為 absolute / fixeddisplay 為 inline-block / flex / grid / flow-root / table-cell / table-captionoverflow 不為 visible (hidden/auto/scroll/clip)contain: layout / content / strict<html>.nav { display: flex; justify-content: space-between; align-items: center; gap: 1rem; }
.card-grid { display: flex; flex-wrap: wrap; gap: 1rem; }
.card-grid > * { flex: 1 1 280px; }
.layout { display: grid; grid-template-columns: 250px 1fr; gap: 1.5rem; }
.sidebar { /* 無需 float */ }
.main { /* 無需 margin 清除 */ }
.article { column-count: 2; column-gap: 2rem; }
float 進行主佈局(2024 年已無此必要)。overflow:hidden 卻有 box-shadow / tooltip / dropdown 溢出需求。.clear、.cf),建議 .clearfix 或語義類名 .layout__clear。display: flow-root 或 Flex/Grid 佈局。.clearfix 隔離影響。浮動的歷史使命是「文繞圖」,而非「佈局」。現代 CSS 給了我們更強、更簡潔、更語義化的佈局工具。清除浮動技巧是歷史包袱,理解 BFC 原理是為了接管舊代碼,新代碼請直接選擇 Flex/Grid/Container Queries。