當容器內子元素全部設為 float 時,父容器高度會塌陷為 0,導致背景、邊框、下方佈局錯亂。本文深度解析 overflow: auto/hidden 建立 BFC(區塊格式化上下文)清除浮動的原理、適用場景、副作用,並對比主流 Clearfix 方案。
<div class="container">
<div class="float-box">浮動內容</div>
<div class="float-box">浮動內容</div>
</div>
<div class="footer">頁腳被頂上來了</div>
.container { background: #f0f0f0; border: 1px solid #ccc; }
.float-box { float: left; width: 100px; height: 100px; background: #333; color: #fff; }
/* 結果:.container 高度為 0,背景不見,footer 貼到浮動元素上方 */
.container {
overflow: hidden; /* 或 auto */
/* IE6/7 觸發 hasLayout */
*zoom: 1;
}
/* 效果:容器高度自適應包含浮動子元素 */
原理:overflow 值為 hidden、auto、scroll 時,會建立新的 BFC,BFC 規範規定計算高度時必須包含浮動子元素。
| 副作用 | 場景 | 解決/規避 |
|---|---|---|
| 剪裁溢出內容 | 子元素有 position:absolute、box-shadow、transform 超出容器 | 改用 Clearfix 偽元素法;或容器加 padding 預留空間 |
| 出現滾動條 | overflow: auto 且內容超出 | 用 overflow: hidden(但同樣剪裁) |
| 觸發滾動鏈 | 內部有 position:sticky 元素 | Sticky 相對最近的 overflow:auto/scroll/hidden 祖先定位,可能破壞預期 |
| 焦點環被剪裁 | 可聚焦元素在邊緣 | 容器加 padding 或改用 Clearfix |
.clearfix::after {
content: "";
display: table; /* 或 block */
clear: both;
}
/* IE6/7 觸發 hasLayout */
.clearfix { *zoom: 1; }
/* 現代簡寫(display: flow-root 同樣建立 BFC,無副作用) */
.clearfix { display: flow-root; } /* IE 不支援,需 @supports 降級 */
<div class="container">
<div class="float-box"></div>
<br class="clearfloat"> <!-- 或 <div class="clearfloat"></div> -->
</div>
.clearfloat { clear: both; height: 0; font-size: 0; line-height: 0; }
| 方案 | 代碼量 | 副作用 | 相容性 | 推薦度 |
|---|---|---|---|---|
| overflow: hidden | 極少 | 剪裁溢出、影響 sticky、焦點環 | IE6+ | ⭐⭐⭐ 簡單場景首選 |
| overflow: auto | 極少 | 可能出現滾動條、同上 | IE6+ | ⭐⭐ 謹慎用 |
| Clearfix ::after | 少 | 幾乎無 | IE8+ (IE6/7 需 zoom) | ⭐⭐⭐⭐⭐ 通用首選 |
| display: flow-root | 極少 | 無 | 現代瀏覽器 | ⭐⭐⭐⭐⭐ 現代首選 |
| 空標籤 clear:both | 多(污染 HTML) | 無 | 全支援 | ⭐ 不推薦 |
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>Float 清除浮動示範</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font: 14px/1.6 system-ui; }
.container { max-width: 960px; margin: 0 auto; padding: 20px; }
.header, .footer { background: #2c3e50; color: #fff; padding: 20px; text-align: center; }
.main { margin-top: 20px; }
.sidebar { float: left; width: 240px; background: #f8f9fa; padding: 20px; }
.content { margin-left: 260px; background: #fff; padding: 20px; border: 1px solid #eee; }
/* Clearfix 套用在 .main 上 */
.main::after { content: ""; display: table; clear: both; }
</style>
</head>
<body>
<header class="header">網站標題</header>
<div class="container">
<div class="main clearfix">
<aside class="sidebar">側邊欄內容</aside>
<div class="content">主內容區域...</div>
</div>
</div>
<footer class="footer">頁腳資訊</footer>
</body>
</html>
新專案請直接使用 Flexbox 或 Grid,原生解決置中、等高、自適應,無需清除浮動:
.main-flex {
display: flex;
gap: 20px;
}
.sidebar { flex: 0 0 240px; }
.content { flex: 1; }
結語:overflow: hidden 是快速修復浮動塌陷的「創可貼」,但副作用明顯。Clearfix 偽元素法 是最穩健的傳統方案;display: flow-root 是現代標準解法。新專案請直接擁抱 Flex/Grid,從根源消除浮動帶來的所有問題。