如何控制粘性元素的子元素的z-index [英] How to control z-index of a child of a sticky element

查看:92
本文介绍了如何控制粘性元素的子元素的z-index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个容器元素,它们具有的位置:粘性 z索引:1

I have two container elements which have position: sticky and a z-index: 1.

其中一个元素的子节点的位置为:绝对

One of those elements has a child node with position: absolute.

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

I would like the child node to be visually on top of both container elements.

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

This is the html structure I must keep and what I have tried:

.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>

当前看起来像这样:

这就是我的方式希望看起来像这样:

This is how I would like it to look:

< img src = https://i.stack.imgur.com/Ybago.png alt =在此处输入图片描述>

但是我希望保持 html 结构和容器粘性对齐方式$ c>元素。

But I would like to keep the html structure and the sticky alignment of the container elements.

推荐答案

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

sticky element will create a stacking context thus all the elements inside cannot be placed relatively to element outside this stacking context. You have to modify the z-index of the first container so it's above the second one with all its child element.

.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>

这篇关于如何控制粘性元素的子元素的z-index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆