0

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>

enter image description here

And here's the F12 computed for the contained <p>.

enter image description here

Shouldn't the margins for <p> be inside the <div>? Obviously they aren't, but why?

InSync
  • 4,851
  • 4
  • 8
  • 30
David Thielen
  • 28,723
  • 34
  • 119
  • 193

1 Answers1

0

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 How to disable margin-collapsing?.

InSync
  • 4,851
  • 4
  • 8
  • 30
  • Every time I think I've seen css at it's screwiest, then I learn something stranger. Anyways, thank you - very well written answer. – David Thielen May 07 '23 at 08:18