【问题标题】:Embedded absolute div and z-index嵌入式绝对 div 和 z-index
【发布时间】:2017-09-14 11:20:18
【问题描述】:

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

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

有没有办法让绝对定位的项目凌驾于其他一切之上?

(由于其他原因我必须使用z-indexes,并且无法使菜单显示:相对)

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

【问题讨论】:

    标签: html css position z-index


    【解决方案1】:

    无需在父 div 中指定 z-index。检查下面更新的 sn-p

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

    根据您的问题,您无法从parent div 中删除z-index,在这种情况下,您可以将更大的z-index 更新为parent div。 检查下面更新的 sn-p...

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

    【讨论】:

    • 由于其他原因(与此问题无关),我必须在父div上使用z-index属性。有没有办法在不删除的情况下解决这个问题?
    • 谢谢,这是我一直在寻找的解决方案。虽然正如您在第一个问题上指出的那样,如果没有 z-index,我不会有问题......所以我正在考虑从项目中删除 z-index 解决方案,它们似乎不是一个好的实践广泛使用。
    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多