Explain Codes LogoExplain Codes Logo

Z-index not working with position absolute

html
responsive-design
positioning
z-index
Nikita BarsukovbyNikita BarsukovΒ·Oct 28, 2024
⚑TLDR

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:

<div style="position: relative;"> // Not your usual magic trick! πŸŽ©πŸ‡ <div style="position: absolute; z-index: 10;">Raised like a curtain</div> <div style="position: absolute; z-index: 5;">Lowered to the audience</div> </div>

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; or position: relative; with a z-index value other than auto.
  • It’s a flexbox or grid item, and its z-index is notauto.
  • Its opacity value is less than 1, even if z-index is auto (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."