【问题标题】:How to control z-index of a child of a sticky element如何控制粘性元素的子元素的 z-index
【发布时间】:2020-06-18 18:12:41
【问题描述】:

我有两个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 对齐方式。

【问题讨论】:

    标签: css alignment z-index sticky


    【解决方案1】:

    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?

    【讨论】:

    猜你喜欢
    • 2013-04-10
    • 2019-11-17
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多