0

I don't understand why I am getting output like this. I was expecting the paragraph elements to be 100px away from all sides.

But I can see that it's not 100px away from the main element, at the top and bottom, instead, the main element moves itself by 100px down, which is not the case in the horizontal direction.

What is the reason for this?

main {
  background-color: aqua;
  width: 50%;
}

p {
  background-color: #444;
  margin: 100px;
}
<main>
  <p>This is a paragraph.</p>
  <p>This is <span class="opposite">another</span> paragraph.</p>
</main>
isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

1

This behavior is called Margin Collapsing. You can read more by visiting the link. But here is an overview:

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing.

It can happen in some well-known cases, but the one you are facing is this one:

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.

And there are several workarounds. One is to set a padding on the parent:

main {
  background-color: aqua;
  padding:1px; /* This padding fixes the callapsing of margin issue */
}

p {
  background-color: #444;
  margin: 100px;
}
<main>
  <p>This is a paragraph.</p>
  <p>This is <span class="opposite">another</span> paragraph.</p>
</main>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65