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

标签 css alignment z-index sticky

我有两个 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>

这是它目前的样子:

enter image description here

这是我希望它看起来的样子:

enter image description here

但我想保留 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>

有关更多详细信息的相关问题:Why can't an element with a z-index value cover its child?

关于css - 如何控制粘性元素的子元素的 z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876047/

相关文章:

css - Bootstrap Canvas z-index 问题

css - 什么有更大的优先级 : opacity or z-index in browsers?

html - Z 索引/显示问题

css - 试图垂直对齐容器 div 中的两个 float div

javascript - 实现 "scroll to top"按钮

css - 列表中图像的垂直对齐

html - 调整窗口大小后将框保持在正确位置

android - 用于包含所有 iPhone 和 Android 手机的最佳单个 CSS 媒体查询最小宽度是多少?

HTML 电子邮件 - Outlook.com 正在将 CSS 样式从一个 DOM 元素移动到另一个

java - JFreeCharts 图例文本和颜色框不对齐