将 div 叠加在具有相同大小的父项之上

Overlay div on top of parent with same size

当我的拖放事件开始时,我需要覆盖一个子项 div 以覆盖它的父项 div,但我无法让子项 div 位于顶部父级使用 z-index。

这是我的 HTML:

<div class="some-element">
  <div class="parent-div">
    <div class="child-div">
      <p>This should be over the parent</p>
    </div>
    <h1>Some text lorem ipsum</h1>
  </div>

  <div class="another-div">
    <p>lorem ipsum</p>
  </div>
</div>

这是我的 CSS

html, body {
  height: 100%;
  width: 100%;
}

.some-element {
  background-color: blue;
  width: 100%;
}

.parent-div {
  background-color: red;
  height: 100%;
  position: relative;
  width: 100%;
  z-index: 1;
}

.child-div {
  background-color: green;
  height: 100%;
  position: relative;
  width: 100%;
  z-index: 999;
}

这是演示我的问题的 CodePen:https://codepen.io/leofontes/pen/LkgJpo

我认为通过使用 z-index 和相对位置我可以实现我想要的,但它似乎没有堆叠在父级之上。知道发生了什么事吗?

对于.child-div,将定位更改为absolute

.child-div {
  background-color: green;
  height: 100%;
  position: absolute;
  width: 100%;
  z-index: 999;
}

html,
body {
  height: 100%;
  width: 100%;
}
.some-element {
  background-color: blue;
  width: 100%;
}
.parent-div {
  background-color: red;
  height: 100%;
  position: relative;
  width: 100%;
  z-index: 1;
}
.child-div {
  background-color: green;
  height: 100%;
  position: absolute;
  width: 100%;
  z-index: 999;
}
<div class="some-element">
  <div class="parent-div">
    <div class="child-div">
      <p>This should be over the parent</p>
    </div>
    <h1>Some text lorem ipsum</h1>
  </div>

  <div class="another-div">
    <p>lorem ipsum</p>
  </div>
</div>

相对定位会将某物相对于其当前位置移动,但会继续占据其原始位置 space。看看下面的例子。当我使用相对定位移动 "text" 段时,请注意文本行不会折叠成 [ 之间的单个 space =50=]"here."

span {
  position: relative;
  top: 20px;
  left: 20px;
  background-color: yellow;
}
<p>
  Some <span>text</span> here.
</p>

当您将一个元素设置为绝对定位时,您将它从正常的文档流中移除。这意味着就其他非绝对定位元素而言,它们不会占用 space 。这就是为什么在使用绝对定位时需要使用 height: 100%; and width: 100%; 来确保子元素与父元素的尺寸匹配。

默认情况下,填充将添加到 100% 尺寸。要防止这种情况,请使用 box-sizing: border-box;.

height: 100%; and width: 100%; 的替代方法是使用 top: 0; right: 0; bottom: 0; left: 0;。这会将子元素拉伸到父元素的边缘。