外層 `
根據 CSS 盒模型規範,**相鄰的垂直外邊距會合併**。當父元素**沒有 Padding、Border、Block Formatting Context (BFC) 觸發條件**時,子元素的 `margin-top` 會「穿透」父元素,與父元素的 `margin-top` 合併,表現為父元素被頂下去。
| 方法 | CSS 代碼 | 原理 | 副作用/注意 |
|---|---|---|---|
| 父元素加 Border | `.parent { border: 1px solid transparent; }` | Border 阻隔外邊距合併 | 佔用 1px 空間,可用 `box-sizing: border-box` 或負 margin 抵消 |
| 父元素加 Padding | `.parent { padding-top: 1px; }` | Padding 阻隔外邊距合併 | 增加內部空間,需調整內部佈局 |
| 父元素觸發 BFC (推薦) | `.parent { overflow: hidden; }` 或 `display: flow-root;` (現代瀏覽器) |
BFC 內部元素外邊距不與外部合併 | `overflow: hidden` 可能剪裁陰絕對定位溢出內容;`flow-root` 純粹觸發 BFC 無副作用 |
| 父元素設定 `display: flex/grid` | `.parent { display: flex; }` | Flex/Grid 容器建立 BFC | 改變內部佈局模式,需配合 `flex-direction: column` 保持垂直排列 |
| 子元素改用 Padding | `.child { padding-top: 20px; }` (移除 margin-top) | Padding 不參與外邊距合併 | 語意不同:Padding 是內部間距,背景色會延伸至 Padding 區 |
| 父元素加 `::before` 偽元素 | `.parent::before { content: ""; display: table; }` | 偽元素阻隔合併 (舊版 clearfix 技巧) | 較繁瑣,不如 overflow 簡潔 |
子元素 `margin-top` 導致父元素下移是 **CSS 標準行為 (Margin Collapsing)**,非 Bug。核心解法是**在父元素建立邊界 (Border/Padding) 或觸發 BFC (`overflow: hidden` / `display: flow-root` / `display: flex`)**。推薦使用 `display: flow-root` 或 Flexbox 佈局,一勞永逸。