为什么 top:0
和 position:absolute
在这里不起作用?
我想提一下,在这种情况下,我无法控制除 .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>
你遇到了collapsing margins .
heatmap
相对于具有 position
的最近祖先定位,不是 static
。这是 body
元素。
body
的第一个 child 有一个 margin-top
。
该边距从 body
的顶部塌陷并将 body 元素向下推离视口(viewport)边缘。
您可以通过对 body 元素应用轮廓来看到这一点。
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>
要避免这种情况,请防止边距塌陷。通过在主体上使用填充而不是在热图上使用边距,最容易做到这一点。
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>