在父级顶部叠加div,大小相同

leo*_*tes 7 html css overlay position z-index

当我的拖放事件开始时,我需要覆盖一个子div来覆盖它的父div,但我无法使用z-index将子div放在父级之上.

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

hun*_*tar 9

用于.child-div改变定位absolute.

.child-div {
  background-color: green;
  height: 100%;
  position: absolute;
  width: 100%;
  z-index: 999;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

相对定位会相对于其当前位置移动某些东西,但会继续占据其原始位置的空间.看看下面的例子.当我使用相对定位来移动"文本"段时,请注意文本行不会折叠到"Some""here"之间的单个空格.

span {
  position: relative;
  top: 20px;
  left: 20px;
  background-color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<p>
  Some <span>text</span> here.
</p>
Run Code Online (Sandbox Code Playgroud)

将元素设置为绝对定位时,将其从正常文档流中取出.这意味着就其他非绝对定位元素而言,它们不会占用空间.这就是为什么height: 100%; and width: 100%;在使用绝对定位时需要使用以确保子元素与父元素的尺寸匹配的原因.

默认情况下,填充将添加到100%维度.为了防止这种使用box-sizing: border-box;.

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