了解 z-index:这个元素如何出现在其父元素的兄弟元素之前?

Understanding z-index: How does this element appear in front of its parent's sibling?

为什么我从.wrapperRed中删除z-index时,红色div在绿色div前面?

感觉z-index是上链继承的

如果我将绿色 div 的 z-index 更改为 6,即使在删除第一句中描述的行后,它仍停留在红色的前面。

.wrapperRed {
  height: 200px;
  width: 200px;
  position: absolute;
  z-index: 1; /* Why is the red div in front of the green one, if this z-index is deleted? */
}

.red {
  position: absolute;
  height: 100%;
  width: 100%;
  background-color: red;
  z-index: 5;
}

.green {
  height: 200px;
  width: 200px;
  background-color: green;
  position: absolute;
  top: 100px;
  left: 100px;
  z-index: 1;
}
<div class="wrapperRed">
  <div class="red"></div>
</div>
<div class="green"></div>

当您从 .wrapperRed 中删除 z-index 时,元素默认为 z-index: auto

在这种情况下,.red.green 都参与相同的堆栈上下文,因为当 z-indexauto 时,定位元素不会创建堆栈上下文(reference).

在此处了解有关 z-index 和堆叠上下文的更多信息:

Why is the .red div in front of the green div when I remove z-index from .wrapperRed?

因为.red不再有parental z-index来约束它。

之前: .redz-index 为 5 在 parental z-index 的范围内1.

After: .redglobal z-index 为 5.

N.B.BeforeAfter 这两种情况下,.wrapperRed 总是 落后于 .green。但是,当它不受约束时,.red(即 .wrapperRed 的宽度和高度的 100%)出现在 .green.

的前面

如果给 parent 和 child divs 不同的背景颜色并使 child div 小于parent.

比较:

.wrapperRed {
  height: 200px;
  width: 200px;
  position: absolute;
  background-color: red;
  z-index: 1;
}

.yellow {
  position: absolute;
  height: 75%;
  width: 75%;
  background-color: yellow;
  
  z-index: 5;
}

.green {
  height: 200px;
  width: 200px;
  background-color: green;
  position: absolute;
  top: 100px;
  left: 100px;
  
  z-index: 1;
}
<div class="wrapperRed">
  <div class="yellow">
  </div>
</div>

<div class="green"></div>

与:

.wrapperRed {
  height: 200px;
  width: 200px;
  position: absolute;
  background-color: red;
}

.yellow {
  position: absolute;
  height: 75%;
  width: 75%;
  background-color: yellow;
  
  z-index: 5;
}

.green {
  height: 200px;
  width: 200px;
  background-color: green;
  position: absolute;
  top: 100px;
  left: 100px;
  
  z-index: 1;
}
<div class="wrapperRed">
  <div class="yellow">
  </div>
</div>

<div class="green"></div>