如何控制粘性元素的子元素的 z-index

How to control z-index of a child of a sticky element

我有两个 container 元素,它们有 position: sticky 和一个 z-index: 1.

其中一个元素有一个带有 position: absolute 的子节点。

我希望子节点在视觉上位于两个 container 元素之上。

这是我必须保留的 html 结构以及我尝试过的结构:

.square {
  height: 100px;
  width: 100px;
  position: absolute;
  background-color: red;
  z-index: 10; /* this doesn't work */
}

.container {
  height: 40px;
  width: 200px;
  position: sticky;
  background-color: blue;
  margin-top: 1rem;
  margin-bottom: 1rem;
  z-index: 1;
}
<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <div class="square"></div>
    </div>
    <div class="container"></div>
  </body>
</html>

这是目前的样子:

这是我希望的样子:

但我想保留 html 结构和 container 元素的 sticky 对齐方式。

sticky 元素将创建一个堆叠上下文,因此内部的所有元素都不能相对于该堆叠上下文之外的元素放置。您必须修改第一个容器的 z-index,使其位于第二个容器及其所有子元素之上。

.square {
  height: 100px;
  width: 100px;
  position: absolute;
  background-color: red;
   /*z-index: 10; this doesn't work */
}

.container {
  height: 40px;
  width: 200px;
  position: sticky;
  background-color: blue;
  margin-top: 1rem;
  margin-bottom: 1rem;
  z-index: 1;
}
.container:first-child {
 z-index:2;
}
<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <div class="square"></div>
    </div>
    <div class="container"></div>
  </body>
</html>

有关更多详细信息的相关问题: