Search code examples
cssalignmentz-indexsticky

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


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:

enter image description here

This is how I would like it to look:

enter image description here

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


Solution

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

    Related question for more details: Why can't an element with a z-index value cover its child?