html - 为什么顶部:0 with position:absolute not working if another element has margin-top here?

标签 html css

<分区>

为什么 top:0position: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>

enter image description here

最佳答案

你遇到了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>

关于html - 为什么顶部:0 with position:absolute not working if another element has margin-top here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514507/

相关文章:

javascript - 在 jQuery Mobile 中使用 $.each 和 wrapInner() 时遇到问题

CSS 3D 转换 - 无法点击链接

html - Bootstrap 4 SCSS 覆盖不起作用

html - 在CSS中的div内水平和垂直居中多个相对div

html - 我应该将图像作为 data/base64 嵌入到 CSS 还是 HTML 中

php - JS 创建的表单元素未提交

html - 当文本分成两行时,Flexbox 用空白填充 div

html - 文本输入边框在表单中被截断

javascript - 使用javascript将python/flask变量注入(inject)HTML表格单元格

css - 缩小浏览器窗口时 HTML div 元素重叠