【问题标题】:Overlay div on top of parent with same size将 div 覆盖在具有相同大小的父对象之上
【发布时间】:2016-08-05 19:26:15
【问题描述】:

当我的拖放事件开始时,我需要覆盖一个子 div 以覆盖它的父 div,但是我无法使用 z-index 让子 div 位于父 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>

这是我的 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 和 position relative 我可以实现我想要的,但它似乎并没有堆叠在父级之上。知道发生了什么吗?

【问题讨论】:

    标签: html css position overlay z-index


    【解决方案1】:

    对于.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>

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

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

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

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

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

    【讨论】:

    • 太棒了!非常感谢,如果我允许,将在 8 分钟内接受您的回答:D
    • 请注意,如果您的子元素有内边距,则 100% 的宽度/高度将无法正常工作,除非您还为其指定了边界框 box-sizing ("box-sizing: border-box;" )。除了使用 100% 的高度/宽度,您还可以使用 "top:0; bottom:0; left:0; right:0;"
    • @EricL,这是正确的。谢谢你的提醒。我会补充我的答案。
    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2016-02-18
    • 2014-07-19
    • 1970-01-01
    相关资源
    最近更新 更多