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

好久不见. 提交于 2019-12-11 16:16:09

问题


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.

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 it currently looks:

This is how I would like it to look:

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


回答1:


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>


来源:https://stackoverflow.com/questions/54876047/how-to-control-z-index-of-a-child-of-a-sticky-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!