0

I have this simple code.

body {
  margin: 0;
  background: white;
}

div {
  background-color: red;
  /*   border: 2px solid black; */
}
<div>
  <p> hello </p>
</div>

The parent div element has a red background. Inside it is a p tag which obviously has a top margin. My understanding is that the child element has a transparent background and so the child element takes the parent's background color including its margin.

If I don't have a border around div element, p tag's margin doesn't get a red background color. But when there is a border it gets. Shouldn't the margin of the child element have the background red as well as the margin of p tag is considered inside the div element?

I have read about margin collapse. In this case, p tag has some default margin. But none of the elements apart from this have any margin. So I guess there is no margin collapse here.

Am I missing something here?

j08691
  • 204,283
  • 31
  • 260
  • 272
Prajwal
  • 563
  • 7
  • 22
  • Does this answer your question? [Why doesn't a child's margin affect a parent's height?](https://stackoverflow.com/questions/27829250/why-doesnt-a-childs-margin-affect-a-parents-height) – flappix Sep 23 '22 at 21:44
  • @flappix actually it doesn't. I still can't get why the child element didn't get the back ground color of the parent as the child p tag has a margin. – Prajwal Sep 23 '22 at 21:58
  • *So I guess there is no margin collapse here.* --> there is a margin collapsing. no margin means a margin equal to 0 so any element has margin (including the div here) – Temani Afif Sep 23 '22 at 22:41
  • @TemaniAfif can you tell me in this case, when margin collapse happens who owns the resultant margin? is it div or p tag? According to the color rendered, it should be div tag(because if it was p tag, it would've acquired the div tag's background color even though it's margin) but the result says div tag. – Prajwal Sep 23 '22 at 23:23

0 Answers0