--- title: 理解邊界重疊的原因 slug: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing ---
有三個標準情況會形成邊界重疊:
<style>
p:nth-child(1){
margin-bottom: 13px;
}
p:nth-child(2){
margin-top: 87px;
}
</style>
<p>下邊界範圍會...</p>
<p>...跟這個元素的上邊界範圍重疊。</p>
<style type="text/css">
section {
margin-top: 13px;
margin-bottom: 87px;
}
header {
margin-top: 87px;
}
footer {
margin-bottom: 13px;
}
</style>
<section>
<header>上邊界重疊是 87</header>
<footer>下邊界重疊還是 87 不能再高了</footer>
</section>
<style>
p {
margin: 0px;
}
div {
margin-top: 13px;
margin-bottom: 87px;
}
</style>
<p>下邊界範圍是 87</p>
<div></div>
<p>...上邊界範圍也是 87。</p>
上面這些情況是會同時發生的,那時邊界重疊的原因又更複雜了。
比較特別的是,當計算的時候某些邊界範圍是負數,邊界重疊的結果會取最大值和最小值相加。舉例來說如果 -13px、8px 和 100px 疊在一起,邊界範圍的計算方法會是 100px - 13px 也就是 87px。
以上這些內容都是發生在 Block-Level 的元素,設定 floating 和 absolutely positioned 的元素完全不用擔心邊界重疊的計算。
| Specification | Status | Comment |
|---|---|---|
| {{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}} | {{Spec2("CSS2.1")}} | Initial definition |