--- title: 外边距重叠 slug: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing tags: - CSS - CSS 盒模型 - 参考 - 指南 translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing ---
块的上外边距(margin-top)和下外边距(margin-bottom)有时合并(折叠)为单个边距,其大小为单个边距的最大值(或如果它们相等,则仅为其中一个),这种行为称为边距折叠。
注意有设定float和position=absolute的元素不会产生外边距重叠行为。
有三种情况会形成外边距重叠:
<style> p:nth-child(1){ margin-bottom: 13px; } p:nth-child(2){ margin-top: 87px; } </style> <p>下边界范围会...</p> <p>...会跟这个元素的上边界范围重叠。</p>
这个例子如果以为边界会合并的话,理所当然会猜测上下2个元素会合并一个100px的边界范围,但其实会发生边界折叠,只会挑选最大边界范围留下,所以这个例子的边界范围其实是87px。
<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>
<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的元素完全不用担心边界重叠的问题。
<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>
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")}} | 初始定义 |