Z-index 不与相同的 DIV 重叠

Z-index doesn't overlap to the same DIVs

问题是重叠的黄色方块——它们应该总是在最上面。

是的,我知道我可以绘制黄色块并使用绝对定位来设置它们。但是...我可以在不更改 HTML 结构的情况下解决这个问题吗?

Codepen Link

.container {
  position: relative;
  margin-bottom: 10px;
  z-index: 1;
}
.green {
  position: sticky;
  left: 0;
  height: 300px;
  width: 300px;
  background: green;
  z-index: 2;
}
.blue {
  position: relative;
  background: blue;
  height: 30px;
  width: 30px;
  left: 50%;
  top: 50%;
  z-index: 3;
}
.yellow {
  position: absolute;
  left: 0;
  top: 30px;
  height: 250px;
  width: 250px;
  background: yellow;
  z-index: 4;
}
<div class="container">
  <div class="green">
    <div class="blue">
      <div class="yellow"></div>
    </div> 
  </div>
</div>
<div class="container">
  <div class="green">
    <div class="blue">
      <div class="yellow"></div>
    </div> 
  </div>
</div>
<div class="container">
  <div class="green">
    <div class="nested">
      <div class="yellow"></div>
    </div> 
  </div>
</div>

html

<div class="container1">
      <div class="green">
        <div class="blue">
          <div class="yellow"></div>
        </div> 
      </div>
    </div>
    <div class="container2">
      <div class="green">
        <div class="blue">
          <div class="yellow"></div>
        </div> 
      </div>
    </div>
    <div class="container3">
      <div class="green">
        <div class="nested">
          <div class="yellow"></div>
        </div> 
      </div>
    </div>

CSS

  .container1 {
      position: relative;
      margin-bottom: 10px;
      z-index: 8;
    }
    .container2 {
      position: relative;
      margin-bottom: 10px;
      z-index: 7;
    }
    .container3 {
      position: relative;
      margin-bottom: 10px;
      z-index: 6;
    }
    .green {
      position: sticky;
      left: 0;
      height: 300px;
      width: 300px;
      background: green;
      z-index: 2;
    }
    .blue {
      position: relative;
      background: blue;
      height: 30px;
      width: 30px;
      left: 50%;
      top: 50%;
      z-index: 3;
    }
    .yellow {
      position: absolute;
      left: 0;
      top: 30px;
      height: 250px;
      width: 250px;
      background: yellow;
      z-index: 1000;
    }

很抱歉,我刚刚通过更改 HTML 代码找到了解决该问题的方法。 你能解释一下绝对位置吗?你想给哪个父元素设置黄色块?

CSS z-index 属性 仅适用于 ---兄弟元素-- -

<div class="a">
  <div class="a1"></div>
</div>
<div class="b">
</div>

在上面的 HTML 片段中,将 z-index 设置为 classes a 和 b 将保持 z-index 但 child a1 在 class a 中将始终保持在 a。因此,当 z-index of class b 等于或大于 class of sibling a, a 的任何 children 都不会在 div b 之上.