Z-index not working with position absolute
To resolve an issue with z-index
not working properly with position: absolute;
, ensure the parent element has a non-static position
(e.g., 'relative'
). The z-index
property only works on positioned elements (not 'static'
). Here's an illustrative example:
In this snippet, the z-index: 10
element appears above the z-index: 5
element, as both reside inside a positioned container, hence respecting the stacking context rules.
Understanding stacking contexts and positioning
Positioning and stacking contexts are fundamental to mastering z-index
.
Why stacking contexts matter
Stacking contexts are imperative for z-index. They're like a party where each z-index
is an invite (RSVP only). If participants aren't in the party, z-index
will just stand near the dip awkwardly.
Creating a stacking context
An element could create a stacking context if:
- It's got
position: absolute;
orposition: relative;
with az-index
value other thanauto
. - Itβs a flexbox or grid item, and its
z-index
is notauto
. - Its
opacity
value is less than 1, even ifz-index
isauto
(doesn't alter stacking order).
Positioning your parent element
Make sure your parent element has a position property set, like relative
, absolute
, fixed
, or sticky
. Otherwise, the kid elements' z-index
will work as effectively as a screen door on a submarine.
Common tumble points & solutions
Overflowed parent container
If the parent container is set to overflow: hidden;
or overflow: auto;
, the child elements might be clipped, causing the z-index
to stage a vanishing act. Set the overflow on the parent container so that the overflowing content is visible.
Mistaking opacity or visibility for z-index
Don't get tripped up by opacity and visibility. Elements with higher z-index but opacity: 0;
or visibility: hidden;
won't be seen, no matter the z-index value.
The stacking context hierarchy, local vs. global
The rule of thumb is don't sneak into global stacking contexts uninvited. Even if an element with bigger z-index
exists in a local stacking context, it might still appear beneath an element with smaller z-index
in a global context. Hence, respect the global-local hierarchy!
Further insight on stacking contexts can be found baked into an excellent resource by Philip Walton titled "What No One Told You About Z-Index."
Was this article helpful?