如何处理堆叠上下文问题

How to deal with stacking context problem

我正在复习堆栈上下文概念,但对以下内容感到困惑 example 在parentdiv中,我们新建了一个stack context,我不明白为什么child stack在parent[=22=之上],我也是参考这张图.

.parent {
  width: 200px;
  height: 100px;
  background: #168bf5;
  position: relative;
  /* Generate new stacking context */
  z-index: 1;
}

.child {
  width: 100px;
  height: 200px;
  background: #32d19c;
  z-index: -1;
}
<div class="box">
  <div class="parent">
    parent
    <div class="child">child</div>
  </div>
</div>

由于您已经为 .parent 创建了一个新的堆叠上下文,因此对其子项设置 z-index 只会更改其相对于同一块的其他子项的堆叠顺序。元素不能在其自身的堆叠上下文之后分层。要将子项置于其父项之后,请使其 z-index 相对于文档(或 DOM 更上层的其他一些共同祖先)工作。

A stacking context is formed... by any...
Element with a position value absolute or relative and z-index value other than auto.
stacking context

.box {
  position: relative;
  /* Generate new stacking context here */
}

.parent {
  width: 200px;
  height: 100px;
  background: #168bf5;
  margin: 0 0 0 40px;
  /* position: relative; */
  /* Do not generate new stacking context here */
}

.child {
  position: relative;
  width: 100px;
  height: 200px;
  background: #32d19c;
  margin: 0 0 0 -40px;
  z-index: -1;
}
<div class="box">
  <div class="parent">
    parent
    <div class="child">child</div>
  </div>
</div>


example you linked, the .box element is set to display:flex. A stacking context is also created when an element "is a child of a flex container, with z-index value other than auto" (stacking context)。我们可以从 .parent 中删除 z-index 值以避免为其提供新的堆叠上下文。

.box {
  display: flex;
}

.parent {
  width: 200px;
  height: 100px;
  background: #168bf5;
  margin: 0 0 0 40px;
  /* z-index: 1; */
  /* Do not generate a new stacking context here */
}

.child {
  width: 100px;
  height: 200px;
  background: #32d19c;
  margin: 0 0 0 -40px;
  position: relative;
  z-index: -1;
}
<div class="box">
  <div class="parent">
    parent
    <div class="child">child</div>
  </div>
</div>