【问题标题】:z-index on sibling absolute elements同级绝对元素上的 z-index
【发布时间】:2016-07-26 17:24:01
【问题描述】:

我试图理解为什么这个例子中的蓝色 div 并不总是在顶部?即红色 div #2 怎么会在蓝色孩子 1 之上。

body {
  padding: 30px;
}
.red1 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  background: red;
}
.red2 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  top: 250px;
  background: red;
}
.blue {
  z-index: 9;
  padding: 10px;
  text-align: center;
  color: white;
  text-transform: uppercase;
  position: absolute;
  top: 100px;
  left: 100px;
  width: 150px;
  height: 130px;
  background: blue;
}
<div class="red1">
  <div class="blue">
    blue child 1
  </div>
</div>
<div class="red2">
  <div class="blue">
    blue child 2
  </div>
</div>

FIDDLE

【问题讨论】:

  • 我希望第一个红色 div 中的蓝色孩子位于红色 div 2 的顶部。两个蓝色 div 的 z-index 均为 9,两个红色的 z-index 均为 1,所以怎么能红色会出现在蓝色之上吗?

标签: html css position z-index


【解决方案1】:

因为.red1.red2 形成不同的堆栈上下文。

一个堆叠上下文中的元素不与另一个堆叠上下文中的元素一起参与。

如果你给.red2 一个z-index: -1,你会得到你期望的行为(demo)。

这是因为.red1.red2 都是绝对定位的,没有定位的祖先。这意味着根元素是它们的直接祖先,the root element forms a stacking context

更多细节在这里:

【讨论】:

    【解决方案2】:

    堆叠上下文——无论是本地的还是根的——遵循一组确定元素堆叠和绘制顺序的规则。堆叠上下文的子项按以下顺序从下到上绘制。如果你翻转订单,你会看到变化。表示 div.red2 然后 div.red1

    【讨论】:

      【解决方案3】:

      body {
        padding: 30px;
      }
      .red1 {
        position: absolute;
        z-index: 1;
        width: 400px;
        height: 200px;
        background: red;
      }
      .red2 {
        position: absolute;
        z-index: 1;
        width: 400px;
        height: 200px;
        top: 250px;
        background: red;
      }
      .blue {
        z-index: 9;
        padding: 10px;
        text-align: center;
        color: white;
        text-transform: uppercase;
        position: absolute;
        top: 100px;
        left: 100px;
        width: 150px;
        height: 130px;
        background: blue;
      }
      <div class="red2">
        <div class="blue">
          blue child 2
        </div>
      </div>
      <div class="red1">
        <div class="blue">
          blue child 1
        </div>
      </div>

      【讨论】:

      • 欢迎来到 StackOverflow!您能否在答案中添加更多详细信息?它会让人们更容易理解它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多