skip to Main Content

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


  1. 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.

    * {
      margin: 0;
      padding: 0;
      border: 0;
    }
    
    body {
      display: flow-root;
    }
    
    .div1 {
      margin: 0rem;
      background: red;
      position: absolute;
    }
    
    .div2 {
      margin: 3rem;
      background: grey;
    }
    <div class="div1">div1</div>
    <div class="div2">div2</div>
    Login or Signup to reply.
  2. Let us go through the docs:

    If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; … then those margins collapse. The collapsed margin ends up outside the parent.

    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, but div2‘s margin is overflowing the body. You can use dev tools to see that, body is much smaller than div2, and is perfectly covering div2‘s bounds.

    enter image description here

    Now since body starts at that level itself, div1 is being setup there itself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search