<div class="box" id="d1">1 (標準流)</div>
<div class="box float" id="d2">2 (左浮動)</div>
<div class="box" id="d3">3 (標準流)</div>
<div class="box float" id="d4">4 (左浮動)</div>
渲染結果:D2 浮起,D3 上移頂替 D2 位置;D4 浮起跟隨 D2 之後;D1、D3 組成新標準流。
核心原則:`clear` 只能影響「使用它的元素本身」,不能影響其他元素。
/* 1. 額外標籤法 (不推薦,污染 HTML) */
<div style="clear:both"></div>
/* 2. Overflow 隱藏法 (觸發 BFC) */
.container { overflow: hidden; } /* 或 auto */
副作用:可能剪切陰影、下拉選單。
/* 3. 偽元素 Clearfix (推薦,IE8+) */
.clearfix::after {
content: ''; display: table; clear: both;
}
.clearfix { zoom: 1; } /* IE6/7 觸發 hasLayout */
/* 4. Flex/Grid 容器 (現代,自動包含浮動) */
.container { display: flex; } /* 或 grid */
浮動元素之間**垂直 margin 不會疊加**;浮動元素與標準流元素的 margin 可能產生預期外的重疊,建議統一用 `padding` 控制內距。