776 字
4 分鐘
CSS margin collapse 排查:子元素的 margin-top 為什麼把父層往下推?
本文目錄
卡片裡的第一個標題有 margin-top: 24px,卡片卻整塊往下移,背景色仍貼著標題頂端。先量卡片上緣和標題上緣。如果兩個位置相同,標題在一般區塊流裡的上外距可能已跟父層折疊。卡片需要自己的內距時,把間距交給父層的 padding;要保留子元素的外距,但讓它留在卡片裡,則在卡片上用 display: flow-root。
用邊界分辨父子折疊和相鄰折疊
在 DevTools 選到卡片後,於 Console 執行下面兩行。假設標題是它的第一個子元素,結果會是兩個以 CSS 像素表示的上緣位置。
const card = $0;[card.getBoundingClientRect().top, card.firstElementChild.getBoundingClientRect().top];若兩個數字相同,但標題的 Computed 仍顯示 margin-top: 24px,可以暫時加 display: flow-root 再量一次。差值變成 24px,就找到外距原先跑到卡片外側的原因。這個診斷適用於以下範例的普通區塊流。父層上緣若已有 border 或 padding,或父層本來就是 flex/grid 容器,先檢查其他版面規則。W3C CSS 2.2 外距折疊規則
另一種折疊發生在相鄰區塊之間。例如前一個元素的下外距是 16px,下一個元素的上外距是 24px,兩個相鄰正外距折疊時,間隔是 24px。若你的疑問是「為什麼沒有 40px」,應量前一個元素的下緣和下一個元素的上緣。
在同一頁量出三種卡片的間距
把這段存成 HTML 開啟。前兩組只差一個 flow-root,第三組則明確由卡片負責內距。最後一組量的是兩個相鄰區塊。
<!doctype html><meta charset="utf-8"><style> .sample { display: flow-root; margin-block: 12px; } .card { background: #e0f2fe; } h2 { margin: 24px 0 0; font: 18px sans-serif; } .contained { display: flow-root; } .padded { padding-block-start: 24px; } .padded h2 { margin-block-start: 0; } .first { margin-block-end: 16px; } .second { margin-block-start: 24px; }</style><div class="sample"><div class="card"><h2>普通卡片</h2></div></div><div class="sample"><div class="card contained"><h2>保留標題外距</h2></div></div><div class="sample"><div class="card padded"><h2>由卡片提供內距</h2></div></div><div class="sample"> <div class="first">前一項</div> <div class="second">下一項</div></div><pre id="result"></pre><script> const cardGaps = [...document.querySelectorAll(".card")].map(card => card.firstElementChild.getBoundingClientRect().top - card.getBoundingClientRect().top ); const siblingGap = document.querySelector(".second").getBoundingClientRect().top - document.querySelector(".first").getBoundingClientRect().bottom; document.querySelector("#result").textContent = JSON.stringify({ cardGaps, siblingGap });</script>預期 cardGaps 為 [0,24,24],siblingGap 為 24。量的是元素盒子的邊緣,文字字形上方本來就可能有留白。
把間距交給負責版面的元素
- 卡片設計需要固定的上下留白,用卡片的
padding-block,把第一個標題原有的上外距清掉。 - 元素來自 Markdown 或共用樣式,想保留其外距,又希望背景色包住外距,使用
flow-root建立新的區塊格式化環境。它也會影響浮動元素的包覆,若卡片裡有浮動圖片,改完一起確認。W3C CSS Display 的 flow-root 定義 - 一列卡片之間要固定有 24px,讓外層 flex 或 grid 管理
gap,並移除重複負責相同間隔的卡片外距。若問題是保留中間距離、只裁掉容器邊緣的子元素外距,可再看 CSS margin-trim 的適用範圍。
參考資料:
CSS margin collapse 排查:子元素的 margin-top 為什麼把父層往下推?
https://laplusda.com/posts/css-margin-collapse-flow-root/