I encountered an issue with setting margin-top on a <p>
element inside a <div>
at the top of the current document. Initially, I expected the margin to be between the div and the p element, but the result showed the margin-top being displayed between the body and the parent div instead. This confusion led me to experiment further.
Upon adding a 1px border to the div.container
, the margin-top was correctly placed between the p element and its parent div.
Furthermore, changing the display
property of div.container
to flex instead of default block allowed the margin-top to function intuitively as well.
This raised the question: Why does this happen? And is there a way to resolve 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>