--- title: 外边距重叠 slug: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing tags: - CSS - CSS 盒模型 - 参考 - 指南 translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing ---
{{CSSRef}}

块的上外边距(margin-top)下外边距(margin-bottom)有时合并(折叠)为单个边距,其大小为单个边距的最大值(或如果它们相等,则仅为其中一个),这种行为称为边距折叠

注意有设定floatposition=absolute的元素不会产生外边距重叠行为。

有三种情况会形成外边距重叠:

同一层相邻元素之间
相邻的两个元素之间的外边距重叠,除非后一个元素加上clear-fix清除浮动
<style>
p:nth-child(1){
  margin-bottom: 13px;
}
p:nth-child(2){
  margin-top: 87px;
}
</style>

<p>下边界范围会...</p>
<p>...会跟这个元素的上边界范围重叠。</p>

这个例子如果以为边界会合并的话,理所当然会猜测上下2个元素会合并一个100px的边界范围,但其实会发生边界折叠,只会挑选最大边界范围留下,所以这个例子的边界范围其实是87px。

没有内容将父元素和后代元素分开
    如果没有边框{{cssxref("border")}},内边距{{cssxref("padding")}},行内内容,也没有创建块级格式上下文清除浮动来分开一个块级元素的上边界{{cssxref("margin-top")}} 与其内一个或多个后代块级元素的上边界{{cssxref("margin-top")}};或没有边框,内边距,行内内容,高度{{cssxref("height")}},最小高度{{cssxref("min-height")}}或 最大高度{{cssxref("max-height")}} 来分开一个块级元素的下边界{{cssxref("margin-bottom")}}与其内的一个或多个后代后代块元素的下边界{{cssxref("margin-bottom")}},则就会出现父块元素和其内后代块元素外边界重叠,重叠部分最终会溢出到父级块元素外面。
<style type="text/css">
    section    {
        margin-top: 13px;
        margin-bottom: 87px;
    }

    header {
        margin-top: 87px;
    }

    footer {
        margin-bottom: 13px;
    }
</style>

<section>
    <header>上边界重叠 87</header>
    <main></main>
    <footer>下边界重叠 87 不能再高了</footer>
</section>
空的块级元素
当一个块元素上边界{{cssxref("margin-top")}} 直接贴到元素下边界{{cssxref("margin-bottom")}}时也会发生边界折叠。这种情况会发生在一个块元素完全没有设定边框{{cssxref("border")}}、内边距{{cssxref("padding")}}、高度{{cssxref("height")}}、最小高度{{cssxref("min-height")}} 、最大高度{{cssxref("max-height")}} 、内容设定为inline或是加上clear-fix的时候。
<style>
​​​​​​p {
  margin: 0;
}
div {
  margin-top: 13px;
  margin-bottom: 87px;
}
</style>

<p>上边界范围是 87 ...</p>
<div></div>
<p>... 上边界范围是 87</p>

一些需要注意的地方:

以上这些内容都是发生在Block-Level的元素,设定floating和absolutely positioned的元素完全不用担心边界重叠的问题。

示例

HTML

<p>The bottom margin of this paragraph is collapsed …</p>
<p>… with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p>

<div>This parent element contains two paragraphs!
  <p>This paragraph has a <code>.4rem</code> margin between it and the text above.</p>
  <p>My bottom margin collapses with my parent, yielding a bottom margin of <code>2rem</code>.</p>
</div>

<p>I am <code>2rem</code> below the element above.</p>

CSS

div {
  margin: 2rem 0;
  background: lavender;
}

p {
  margin: .4rem 0 1.2rem 0;
  background: yellow;
}

结果

{{EmbedLiveSample('示例', 'auto', 350)}}

规范

Specification Status Comment
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}} {{Spec2("CSS2.1")}} 初始定义

参见