Why top: 0 with position: absolute doesn't work if the other element has margin-top here?

Why top:0

to position:absolute

not work here?

I want to mention that in this state I have no control over any other element other than .heatmap

body {
  position: relative;
  margin: 0;
  padding: 0
}

.section1 {
  margin-top: 107px;
  border: 1px solid green
}

.heatmap {
  z-index: 2147483642;
  top: 0px;
  left: 0px;
  position: absolute;
  width: 1425px;
  height: 1110px;
  opacity: 0.7;
  background: red
}
      

<div class="section1">something</div>

<div class="heatmap">hamara heatmap</div>
      

Run codeHide result


enter image description here

+3


source to share


3 answers


You are faced with collapsing fields .

heatmap

positioned relative to the nearest ancestor, which has position

, which is not static

. This is the element body

.

The first child body

has a margin-top

.

This edge collapses at the top body

and pushes the body element down from the edge of the viewport.

This can be seen by applying an outline to the body element.



body {
  position: relative;
  margin: 0;
  padding: 0;
  outline: solid pink 10px;
}

.section1 {
  margin-top: 107px;
  border: 1px solid green
}

.heatmap {
  z-index: 2147483642;
  top: 0px;
  left: 0px;
  position: absolute;
  width: 1425px;
  height: 1110px;
  opacity: 0.7;
  background: red
}
      

<div class="section1">something</div>

<div class="heatmap">hamara heatmap</div>
      

Run codeHide result


To avoid this, do not allow the collapse of the fields. This is most easily accomplished by using a shim on the body instead of the field on the heatmap.

body {
  position: relative;
  margin: 0;
  padding: 107px 0 0 0;
  outline: solid pink 10px;
}

.section1 {
  border: 1px solid green
}

.heatmap {
  z-index: 2147483642;
  top: 0px;
  left: 0px;
  position: absolute;
  width: 1425px;
  height: 1110px;
  opacity: 0.7;
  background: red
}
      

<div class="section1">something</div>

<div class="heatmap">hamara heatmap</div>
      

Run codeHide result


+5


source


You just remove position: relative

from body

, it will work



body {
  margin: 0;
  padding: 0
}

.section1 {
  margin-top: 107px;
  border: 1px solid green
}

.heatmap {
  z-index: 2147483642;
  top: 0px;
  left: 0px;
  position: absolute;
  width: 1425px;
  height: 1110px;
  opacity: 0.7;
  background: red
}
      

<div class="section1">something</div>

<div class="heatmap">hamara heatmap</div>
      

Run codeHide result


0


source


Just give padding-top: 1px; into the body and it will work fine;

The problem was the margin was given to section 1 which causes the field to collapse

See this link:

https://css-tricks.com/what-you-should-know-about-collapsing-margins/

0


source







All Articles