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

Sam*_*ton 2 css z-index alignment sticky

我有两个container元素,它们有position: sticky和 a 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;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <div class="square"></div>
    </div>
    <div class="container"></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是它目前的样子:

在此处输入图片说明

这是我希望它的外观:

在此处输入图片说明

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

Tem*_*fif 7

stickyelement 将创建一个堆叠上下文,因此内部的所有元素不能相对于该堆叠上下文之外的元素放置。您必须修改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;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <div class="square"></div>
    </div>
    <div class="container"></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息的相关问题:为什么具有 z-index 值的元素不能覆盖其子元素?