Home > Enterprise >  Absolutely postioned div moving with margin top of another static postioned div
Absolutely postioned div moving with margin top of another static postioned div

Time:12-26

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 ></div>
<div ></div>

CodePudding user response:

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 ></div>
<div ></div>

CodePudding user response:

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;
  z-index:1;
  
}

.div-2 {
  height: 200px;
  width: 90%;
  background-color: blueviolet;
  top: 8rem;
  position: inherit;
  
}

Use top and position inherit instead of margin-top, check if it can be use.

  • Related