浮動元素脫離文檔流,導致父容器高度塌陷為 0,影響後續佈局。本課系統講解 4 種主流清除方案的原理、適用場景與優劣對比。
<div class="parent">
<div class="child float-left">左浮動</div>
<div class="child float-right">右浮動</div>
</div>
<div class="footer">Footer 跑到頂部了!</div>
/* 現象:.parent 高度為 0,.footer 緊貼 .parent 上方 */
| 方案 | 代碼 | 原理 | 優點 | 缺點 | 推薦指數 |
|---|---|---|---|---|---|
| 1. 額外標籤法 | <div style="clear:both"></div> |
新增塊級元素 clear:both | 通俗易懂、兼容最好 | 污染 HTML 結構、語義化差 | ⭐ (不推薦新項目) |
| 2. 父級 overflow | .parent { overflow: hidden; } |
觸發 BFC (塊級格式化上下文) | 代碼極少、無額外標籤 | 陰影/絕對定位子元素會被裁剪 | ⭐⭐⭐ (簡單場景首選) |
| 3. 偽元素 :after (Clearfix) | .clearfix::after { content:""; display:block; clear:both; } |
CSS 偽元素模擬額外標籤 + BFC | 不污染 HTML、復用性強、業界標準 | 需兼容 IE6/7 (zoom:1) | ⭐⭐⭐⭐ (經典項目標配) |
| 4. Flex/Grid 現代佈局 | .parent { display: flex; } |
Flex/Grid 容器自動包含浮動子項 (非浮動機制) | 根治浮動問題、功能最強、代碼最少 | IE10+ 部分支援、需學習新佈局模型 | ⭐⭐⭐⭐⭐ (新項目首選) |
觸發條件 (任一):
BFC 渲染規則:
.clearfix::before,
.clearfix::after {
content: "";
display: table; /* table 創建匿名表格盒子,配合 after clear:both */
}
.clearfix::after {
clear: both;
}
.clearfix {
*zoom: 1; /* IE6/7 觸發 hasLayout */
}