Search code examples
htmlcssposition

Absolutely postioned div moving with margin top of another static postioned div


I have a body containing two div's one is an absolutely positioned div and another one is a static default positioned div, i want the absolutely positioned div to take the full height of the screen which it takes but the problem that next arises is when i try to apply margin top to the statically positioned div, it also gets added to the absolutely positioned div.

How can I make the absolutely positioned div not get the margin of the sibling div ?

body {
  font-family: sans-serif;
  margin: 0;
  padding: 0;
  position: relative;
}

.div-1 {
  position: absolute;
  border: 2px solid red;
  width: 90%;
  left: 0;
  right: 0;
  margin: 0 auto;
  height: 100vh;
}

.div-2 {
  height: 200px;
  width: 90%;
  background-color: blueviolet;
  margin-top: 8rem;
}
<div class="div-1"></div>
<div class="div-2"></div>


Solution

  • The issue is that you have margin collapse on the body element. Margin collapse happens when there's no content separating parent and descendants elements (such as the body and .div-2). You can easily fix this by setting the display property of the body element to flow-root.

    body {
      font-family: sans-serif;
      margin: 0;
      padding: 0;
      position: relative;
      /* Set flow-root */
      display: flow-root;
    }
    
    .div-1 {
      position: absolute;
      border: 2px solid red;
      width: 90%;
      left: 0;
      right: 0;
      margin: 0 auto;
      height: 100vh;
    }
    
    .div-2 {
      height: 200px;
      width: 90%;
      background-color: blueviolet;
      margin-top: 8rem;
    }
    <div class="div-1"></div>
    <div class="div-2"></div>