3

Why top:0 with position:absolute not working here?

I want to mention that in this condition I don't have control on 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>

enter image description here

Jitendra Vyas
  • 148,487
  • 229
  • 573
  • 852

3 Answers3

5

You have encountered collapsing margins.

heatmap is positioned with respect to the nearest ancestor which has position that is not static. This is the body element.

The first child of the body has a margin-top.

That margin collapses through the top of the body and pushes the body element down away from the viewport edge.

You can see this 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>

To avoid this, prevent the margins from collapsing. This is most easily done by using padding on the body instead of margin 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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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>
Super User
  • 9,448
  • 3
  • 31
  • 47
0

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

The problem was margin given to section1 which cause collapsing margin

See this link:

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

Rakesh Soni
  • 1,293
  • 2
  • 11
  • 27