CSS stacking context
Chances are that you also added the position: relative
beside the z-index
value when you wanted to change the element's position along the z-axis.
By adding position
, you are creating a stacking context, and without a stacking context, the z-index
does not take effect. But that's just one of the many ways to create such contexts.
It is also created whenever you set the display
to flex
or grid
, or use the less known isolation
property.
The next time you automatically add the position
, pause for a moment because it might not be necessary to do it and can save you from potential undesired side effects. Or better, set up a linter to catch it.
If you want to a deep dive into z-index
, then check the What the heck, z-index?? article.