z-index controls stacking order for positioned elements within the same stacking context. Higher values appear on top, but only for elements that create/participate in a stacking context (e.g., position with z-index, opacity, transform). Stacking contexts cause most bugs, so test layering with position, opacity, and transforms.
How does z-index work in CSS?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
The z-index property specifies the stacking order of positioned elements (elements with position other than static). Elements with higher z-index values appear on top of those with lower values when they overlap.
Value Type | Example | Meaning |
|---|---|---|
Auto | z-index: auto; | Default stacking within the same context. |
Positive Integer | z-index: 10; | Element appears above those with smaller values. |
Negative Integer | z-index: -1; | Element appears below normal stacking order. |
Example: Layering Elements
.box1 { position: relative; z-index: 1; background: lightblue; }
.box2 { position: relative; z-index: 2; background: coral; }
.box3 { position: relative; z-index: 0; background: lightgreen; }
In this example, .box2 appears above .box1 and .box3 because it has the highest z-index value.
Stacking Context
Each positioned element with a z-index forms a new stacking context. Elements inside one context are layered relative to each other but cannot overlap elements outside that context. Contexts are created by certain properties like:
position(relative, absolute, fixed) with z-index.opacity: 1transform,filter, orperspective.isolation: isolate;
Common Pitfalls
- Setting
z-indexon an element without a positioning context (e.g.,position: static) has no effect. - Nested stacking contexts can cause confusion — an element may appear behind another even if it has a higher z-index, depending on its parent’s context.
Debugging Tip
Use browser developer tools to inspect stacking contexts. Understanding which context your element belongs to is key to resolving unexpected layering issues.
Practical scenario
Ensure a dropdown appears above a sticky header and modal overlay.
Common pitfalls
- Forgetting z-index only works on positioned elements.
- Creating new stacking contexts with transforms or opacity.
- Using huge z-index values without a scale.
Central z-index scales reduce chaos. Test overlays in combination (dropdown + modal).
Think of z-index like layers in Photoshop — each element lives on a sheet. The higher the z-index, the closer to your eyes it appears. But if it's in a different folder (stacking context), it can’t overlap layers in another folder.
z-indexcontrols visual stacking of positioned elements.- Works only inside stacking contexts.
- Higher values appear above lower ones.
- Context isolation can cause seemingly incorrect overlaps — always check parent elements.