首页 > 解决方案 > 当父级的 z-index 与另一个 div 相等时,子级的 z-index 较高会隐藏绝对子级

问题描述

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

我有 2 个主要 div,它们都是z-index: 2. 在第一个 div 里面,我有一个childwho z-index is 99999,现在,因为relativestatic都被浏览器以先来后到的方式处理,也就是说,div2 的顺序比 div1 高,我的绝对child里面div1会在后面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。

标签: htmlcssz-index

解决方案


增加z-index父项 ( #item1) 或从两个父项中删除 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>


推荐阅读