Z-index & Stacking Context
Control the depth of overlapping elements, and understand why a z-index of 9999 sometimes refuses to work.
What it is
While position lets you move elements around on the X and Y axes, z-index controls the Z-axis—depth.
When elements overlap, the browser needs to know which one should be rendered in front of the other. By default, elements that come later in your HTML code will overlap elements that came earlier. The z-index property allows you to override this order by assigning integer values. Higher numbers are closer to the user.
Why it matters
Without z-index, UI components like sticky navigation bars, dropdown menus, and modal popups would be drawn behind the normal content of your page, rendering them unusable.
How it works
To use z-index, two conditions must be met:
1. The element must have a position value other than static (e.g., relative, absolute, fixed, sticky). Note: Flexbox and Grid children can also use z-index without being explicitly positioned.
2. You assign an integer (positive, negative, or zero). For example: z-index: 10.
It is a best practice to use a defined scale (like 10, 20, 30, 40) rather than randomly typing 999 or 99999. This leaves room to insert new layers between existing ones later.
Try it
Toggle the z-index on Parent A. Watch how giving it z-index: 1 traps the red child (which has z-index: 9999) completely behind Parent B.
The Stacking Context Trap
Controls
Apply z-index: 1 to Parent A. Watch how it creates a sealed folder, trapping the child's 9999 behind Parent B's 2.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
z-indexrequiresposition(relative, absolute, fixed, or sticky).- Higher integer numbers render in front of lower numbers.
- A parent with a
z-indexcreates a 'Stacking Context' (a sealed folder). - A child with
z-index: 9999cannot escape a parent whosez-indexis lower than a sibling.
Done with this concept?
Mark it complete to track your progress. No login needed.