Search code examples
htmlcssz-index

How to beat a sibling stacking context with the highest z-index value


Given the following situation, how could you ensure that .green would appear above .blue by only modifying the CSS of .green? .blue has the highest z-index value possible of 2147483647 and cannot be changed.

My understanding is that these two elements already have their own stacking contexts, so no trickery like transform: scale(1) would work here.

Is there a way to do it?

div {
  width: 200px;
  height: 100px;
}

.green {
  background: green;
  position: relative;
  z-index: 999;
}

.blue {
  background: blue;
  position: absolute;
  margin-top: -50px;
  margin-left: 50px;
  z-index: 2147483647; // maximum value
}
<div class="green">Must appear above</div>
<div class="blue">Cannot modify</div>


Solution

  • 3D transform can do it but pay attention to the potential side effects of transform:

    div {
      width: 200px;
      height: 100px;
    }
    
    .green {
      background: green;
      position: relative;
      z-index: 999;
      transform: translateZ(1px); /* 1px is enough */
    }
    
    .blue {
      background: blue;
      position: absolute;
      margin-top: -50px;
      margin-left: 50px;
      z-index: 2147483647; /* maximum value */
    }
    
    body {
      transform-style:preserve-3d; /* this is mandatory*/
    }
    <div class="green">Must appear above</div>
    <div class="blue">Cannot modify</div>

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