嵌入式绝对div和z-index

时间:2017-09-14 11:20:19

标签: html css position z-index

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

我在下拉菜单中使用position:relative(因此它会显示在打开它的按钮下方)。问题是,下拉菜单只覆盖它的父div:如果下拉菜单重叠到另一个(非父)div,无论我设置的z-index,它都是底层。

是否有解决方案使绝对定位项目超过其他所有项目?

(由于其他原因我必须使用z-index,我不能显示菜单: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>

1 个答案:

答案 0 :(得分:3)

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

&#13;
&#13;
.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;
}
&#13;
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>
&#13;
&#13;
&#13;

  

根据您的问题,您无法从z-index移除parent div,在这种情况下,您可以将更高z-index更新为parent div。   查看下面的更新代码段...

&#13;
&#13;
.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;
}
&#13;
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>
&#13;
&#13;
&#13;