1

So I have a div with a p inside at the top of current document. And I'm setting margin-top onto the <p> expecting there could be a margin between the div and p elememt. What makes me misunderstanding is the result that the margin-top is shown between the body and the parent div. See the example.

But if I set the div.container with a 1px border, the margin-top could be brought back between the p element and its parent div.

What's more, if the div.container is set as flex display instead of default block, the margin-top could work intuitively as well.

How come? And can I do anything about it?

html, body {
  padding: 0;
  margin: 0;
  background-color: grey;
}

.container {
  background-color: red;
  display: block; /* flex could also make it work */
  margin: 0;
  /* The border setting would bring back the margin-top on p */
  /* border: 1px solid black; */
}

.paragraph {
  margin-top: 100px;
}
<div class="container">
<p class="paragraph"> sadf </p>
</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
千木郷
  • 1,595
  • 2
  • 19
  • 30

1 Answers1

3

html, body {
  padding: 0;
  margin: 0;
  background-color: grey;
}

.container {
  background-color: red;
  display: block; /* flex could also make it work */
  margin: 0;
  overflow: hidden;
  /* The border setting would bring back the margin-top on p */
  /* border: 1px solid black; */
}

.paragraph {
  margin-top: 100px;
}
<div class="container">
<p class="paragraph"> sadf </p>
</div>

It is all about vertical margin collapse.

the quickest solution is adding overflow: hidden; for parent element.

You learn more about vertical margin collapse here

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

As you can in edited snippet it is fixed.

Hovhannes Sargsyan
  • 1,063
  • 14
  • 25
  • I've learned margin collapse before, but why the margin-top of children element could have affect on parent container makes me still unable to understand relation to the design of margin collapse. Could you provide some more detailed advices? – 千木郷 May 04 '19 at 17:30
  • @千木郷 This post might help you: https://stackoverflow.com/questions/19718634/how-to-disable-margin-collapsing – Mobarak Ali May 04 '19 at 19:07