-1

div {
  background: gray;
  width: 200px;
  height: 200px;
}

p {
  margin-top: 24px;
  margin-bottom: 24px;
  color: white;
  padding: 5px;
  width: 100px;
}

.one {
  background: orange;
  outline: 2px solid blue;
}

.two {
  background: lightskyblue;
  outline: 2px solid red;
}
<div>
  <p class="one">Paragraph One</p>
  <p class="two">Paragraph Two</p>
</div>

Why is the margin collapsing for the first paragraph? i.e. why is the first paragraph touching the div container?

Ibram Reda
  • 1,882
  • 2
  • 7
  • 18

1 Answers1

0

Because both elements (div and p) belong to the same Block formatting context Therefore their margins collaps, margin collapsing is a property of the Block formatting context by design.


If you want to prevent this, Make the <div> establish it's own Block formatting context.

You can achieve this in numerous ways as described in the MDN

Here i used overflow:auto on the <div>

div {
  background: gray;
  width: 200px;
  height: 200px;
  
  /* NEW */
  overflow:auto
}

p {
  margin-top: 24px;
  margin-bottom: 24px;
  color: white;
  padding: 5px;
  width: 100px;
}

.one {
  background: orange;
  outline: 2px solid blue;
}

.two {
  background: lightskyblue;
  outline: 2px solid red;
}
<div>
  <p class="one">Paragraph One</p>
  <p class="two">Paragraph Two</p>
</div>
Rainbow
  • 6,772
  • 3
  • 11
  • 28