嵌入式绝对 div 和 z-index

Embedded absolute div and z-index

我尝试实现一个下拉菜单,它可以在不同的 div 中重复使用。

我使用 position:relative 作为下拉菜单(因此它会出现在打开它的按钮下方)。问题是,下拉菜单仅覆盖其父级 divs:如果下拉菜单与另一个(非父级)div 重叠,则无论我设置的 z-index 是多少,它都会覆盖。

有没有办法让绝对定位的项目覆盖其他所有项目?

(我因为其他原因必须使用z-indexes,我无法制作菜单display:relative)

.back, .front, .back2{
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.back {
  position:relative;
  z-index: 10;
  top: 20px;
  left: 20px;
  background: red;
}
.back2 {
  position:relative;
  z-index: 10;
  top: 50px;
  left: 20px;
  background: orange;
}

.front {
  position: absolute;
  z-index:20;
  top: 60px;
  left: 60px;
  background: green;
}
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>

无需在父级中提供 z-index div。检查下面更新的代码段

.back, .front, .back2{
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.back {
  position:relative;
  top: 20px;
  left: 20px;
  background: red;
}
.back2 {
  position:relative;
  top: 50px;
  left: 20px;
  background: orange;
}

.front {
  position: absolute;
  z-index:20;
  top: 60px;
  left: 60px;
  background: green;
}
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>

As per your question you can't remove z-index from parent div in that case you can update greater z-index to parent div. Check updated snippet below...

.back, .front, .back2{
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.back {
  position:relative;
  top: 20px;
  left: 20px;
  background: red;
  z-index:10;
}
.back2 {
  position:relative;
  top: 50px;
  left: 20px;
  background: orange;
  z-index:9;
}

.front {
  position: absolute;
  z-index:20;
  top: 60px;
  left: 60px;
  background: green;
}
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>