Search code examples
htmlcss

Div with position:absolute moved by sibling div's margin


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>


Solution

  • 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>