英文:
How/why does an inner element have its margins extend into a containing element?
问题
Some very simple html:
<header class="my-header">
    <div class="no-margins">
        <p>Nicolay Copy</p>
    </div>
</header>
And css:
.my-header {
    position: sticky;
    top: 0;
    margin: 0 0 0 0;
    background-color: white;
    z-index: 1;
}
.no-margins {
    margin: 0 0 0 0;
}
Here's the F12 computed for the containing <div>:
And here's the F12 computed for the contained <p>.
Shouldn't the margins for <p> be inside the <div>? Obviously they aren't, but why?
英文:
Some very simple html:
<header class="my-header">
    <div class="no-margins">
        <p>Nicolay Copy</p>
    </div>
</header>
And css:
.my-header {
    position: sticky;
    top: 0;
    margin: 0 0 0 0;
    background-color: white;
    z-index: 1;
}
.no-margins {
    margin: 0 0 0 0;
}
Here's the F12 computed for the containing <div>
And here's the F12 computed for the contained <p>.
Shouldn't the margins for <p> be inside the <div>? Obviously they aren't, but why?
答案1
得分: 0
根据文档:
> 如果没有边框、填充、内联部分、块级格式化上下文或用于分隔块的 margin-top 与一个或多个后代块的 margin-top,或者没有边框、填充、内联内容、height 或 min-height 用于分隔块的 margin-bottom 与一个或多个后代块的 margin-bottom,那么这些边距会合并。合并后的边距最终位于父级之外。
>
> – 掌握边距合并 | MDN Web 文档
由于.no-margins和p之间没有任何内容,它们的第一个和最后一个子元素,它们的margin-top和margin-bottom会合并。.no-margin的边距都为0,因此它们的margin-top和margin-bottom作为一个整体,最终采用p的值。
有关解决方案,请参见https://stackoverflow.com/q/19718634。
英文:
According to the docs:
> If there is no border, padding, inline part, block formatting context
> created, or clearance to separate the margin-top of a block from the
> margin-top of one or more of its descendant blocks; or no border,
> padding, inline content, height, or min-height to separate the
> margin-bottom of a block from the margin-bottom of one or more of its
> descendant blocks, then those margins collapse. The collapsed margin
> ends up outside the parent.
>
> – Mastering margin collapsing | MDN Web Docs
Since there is nothing between .no-margins and p, its first and last child, their margin-top and margin-bottom collapse. .no-margin's margins are all 0, so their margin-top and margin-bottom, as a whole, ultimately take p's as the value.
For solutions, see https://stackoverflow.com/q/19718634.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。




评论