Why is div1
being pushed from the top edge? It seems to follow div2
margin setting.
I would expect div1
to behave independently of div2
(i.e. stick to the top). Is there any way to keep div1
at the top of the screen without using top:0
.
* {
margin: 0;
padding: 0;
border: 0;
}
.div1 {
margin: 0rem;
background: red;
position: absolute;
}
.div2 {
margin: 3rem;
background: grey;
}
<div class="div1">div1</div>
<div class="div2">div2</div>
2
Answers
It is because of margin collapsing between div2 and its parent. The margin ends up outside the parent.
One way is to set
display:flow-root
on the parent container to establish a new block formatting context for its contents which prevents this margin collapsing.In your example the parent container is
body
.Let us go through the docs:
Margin collapse is when margins of multiple elements combine together.
So what actually happens is that the body’s content is the whole of
div2
, butdiv2
‘s margin is overflowing thebody
. You can use dev tools to see that, body is much smaller than div2, and is perfectly coveringdiv2
‘s bounds.Now since body starts at that level itself,
div1
is being setup there itself.