内部元素为什么会将其边距扩展到包含元素中?

huangapple go评论66阅读模式
英文:

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:

&lt;header class=&quot;my-header&quot;&gt;
    &lt;div class=&quot;no-margins&quot;&gt;
        &lt;p&gt;Nicolay Copy&lt;/p&gt;
    &lt;/div&gt;
&lt;/header&gt;

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 &lt;div&gt;

内部元素为什么会将其边距扩展到包含元素中?

And here's the F12 computed for the contained &lt;p&gt;.

内部元素为什么会将其边距扩展到包含元素中?

Shouldn't the margins for &lt;p&gt; be inside the &lt;div&gt;? Obviously they aren't, but why?

答案1

得分: 0

根据文档:

> 如果没有边框、填充、内联部分、块级格式化上下文或用于分隔块的 margin-top 与一个或多个后代块的 margin-top,或者没有边框、填充、内联内容、heightmin-height 用于分隔块的 margin-bottom 与一个或多个后代块的 margin-bottom,那么这些边距会合并。合并后的边距最终位于父级之外。
>
> – 掌握边距合并 | MDN Web 文档

由于.no-marginsp之间没有任何内容,它们的第一个和最后一个子元素,它们的margin-topmargin-bottom会合并。.no-margin的边距都为0,因此它们的margin-topmargin-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.
>
> &ndash; 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.

huangapple
  • 本文由 发表于 2023年5月7日 15:20:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定