【问题标题】:Higher z-index of a child when parent is equal z-index with another div hides the absolute child [duplicate]当父级的z-index与另一个div相等时,子级的z-index较高会隐藏绝对子级[重复]
【发布时间】:2020-02-14 13:58:17
【问题描述】:

我有一个约束:这两个父 div 不能是“一个高于另一个”,它们的重要性相同。

我有 2 个主 div,它们都是 z-index: 2。在第一个 div 中,我有一个 childz-index is 99999,现在,因为 relativestatic 都被浏览器以先来后到的方式处理,也就是说,div2 有比 div1 更高的顺序,我在 div1 中的绝对 child 将落后于 div2。观看:

#item1 {
  width: 100%;
  height: 200px;
  background-color: gray;
  position: relative;
  z-index: 2;
}

#child {
  position: absolute;
  bottom: -15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: white;
  z-index: 15;
}

#item2 {
  width: 100%;
  height: 200px;
  background-color: green;
  position: relative;
  z-index: 2;
}
<div id="item1">
  <div id="child">
  </div>
</div>
<div id="item2">
</div>

我在这里缺少什么?据说网络上充满了relative 的 div,它们一个接一个地出现,它们里面有绝对的 div。

【问题讨论】:

  • 我认为子元素的 z-index 不能高于其父元素。尝试将 div1 z-index 设为 3。
  • @LoiNguyenHuynh 所以,如果我要正确理解所有这些,我只是在脑海中遇到了一个悖论。不可能有一个项目不比另一个更高。没有“同等级别”这样的东西,一个项目总是高于另一个——那么问题是,作为开发人员,我决定哪一个项目在视图方面更重要。对吗?
  • 还有一个叫做painting order的东西。如果元素没有相互重叠,则它们可能是同时绘制的(或者如您所说的“相等级别”)。如果它们重叠,则后面绘制的将比提前绘制的“在视图方面更重要”。
  • @LoiNguyenHuynh 好吧,当然,但我说的是 2 个普通 div,staticrelative 具有相同的 z-index。 DOM 中的另一层被赋予绘制优先级,是吗?除此之外,还有一些项目可能会触发该订单的重新构建,但如果我们只是以这个基本示例为例,那就是它的工作原理。

标签: html css z-index


【解决方案1】:

增加父项 (#item1) 的 z-index 或从两个父项中删除 z-index。它会起作用的。

实际上你不需要在父元素中使用z-index,如果你需要使用z-index然后给第一个父元素更高,浏览器在第二个元素上给予更高的优先级(z-index)因为浏览器需要在第一个元素上显示第二个元素。

#item1 {
  width: 100%;
  height: 200px;
  background-color: gray;
  position: relative;
}

#child {
  position: absolute;
  bottom: -15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: white;
  z-index: 15;
}

#item2 {
  width: 100%;
  height: 200px;
  background-color: green;
  position: relative;
}
<div id="item1">
  <div id="child">
  </div>
</div>
<div id="item2">
</div>

【讨论】:

  • 这行得通,但是,对不起,我用我的一个约束更新了我的问题。
  • 我已经更新了我的答案,检查一下
【解决方案2】:
enter code here

#item1 {
  width: 100%;
  height: 200px;
  background-color: gray;
  position: relative;
  z-index: 2;
}

#child {
  position: absolute;
  top: -15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: white;
  z-index: 9999;
}

#item2 {
  width: 100%;
  height: 200px;
  background-color: green;
  position: relative;
  z-index: 2;
}
<div id="item1">
  
</div>
<div id="item2">
  <div id="child">
  </div>
</div>

【讨论】:

  • 你应该在 item2 中使用 id child。然后它的工作完美
  • 这行得通,但是,对不起,我用我的一个约束更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多