π Introduction
The z-index property in CSS controls the stacking order of elements β meaning which element appears on top when elements overlap. It is essential when building UI components like modals, dropdowns, tooltips, sticky headers, and layered designs. Understanding z-index requires understanding **positioning** and **stacking contexts**. π§ β¨
π― What Does z-index Affect?
- Controls which element appears in front or behind
- Works only on positioned elements (relative, absolute, fixed, sticky)
- Creates new stacking contexts in certain conditions
- Critical for building layered UI systems
β¨ Syntax
Syntax
selector {
z-index: <number> | auto;
}Note
(position: relative, absolute, fixed, sticky)
π§© z-index Values
1. auto (default)
Uses the natural stacking order based on HTML flow, without forcing a new layer.
auto
z-index: auto;2. Positive Numbers
Higher value β element appears above others.
positive
z-index: 10;3. Negative Numbers
Allows placing element behind others in the stacking order.
negative
z-index: -1;π₯ Important Concept: Stacking Context
A **stacking context** is like a special layer that contains its own set of z-index rules. Elements inside one stacking context cannot overlap elements in a different oneusing z-index alone.
π§ When is a new stacking context created?
- An element with position + z-index other than auto
opacity < 1transformapplied (e.g., scale, rotate)filterappliedisolation: isolatemix-blend-modewill-change
Note
π₯ Practical Examples
1. Basic Layering
Basic Example
.top {
position: relative;
z-index: 10;
}
.bottom {
position: relative;
z-index: 1;
}2. Using Negative z-index
Negative
.behind {
position: relative;
z-index: -1;
}3. Modal Over Everything
Modal
.modal {
position: fixed;
z-index: 9999;
inset: 0;
}4. Bug Example: transform creates stacking context
transform issue
.parent {
transform: scale(1);
z-index: 1;
}
.child {
position: absolute;
z-index: 9999; /* won't escape the parent stacking context */
}5. Tooltip Example
Tooltip
.tooltip {
position: absolute;
z-index: 100;
}6. Header Above Content
Sticky Header
header {
position: sticky;
top: 0;
z-index: 50;
}π Stacking Order (Default without z-index)
| Order (lowest β highest) | What |
|---|---|
| 1 | background/border |
| 2 | normal content |
| 3 | positioned elements (z-index: auto) |
| 4 | positioned elements with z-index |
π§ Tips to Avoid z-index Bugs
- Always check if an element creates a stacking context
- Keep a z-index scale (e.g., 100 for popup, 1000 for modal)
- Use
isolation: isolate;to control stacking contexts - Avoid unnecessarily large z-index values
- Debug using browser DevTools β Layers panel
π Conclusion
The z-index property is vital for controlling how elements overlap in modern UIs. But it becomes truly powerful only when paired with an understanding of stacking contexts and positioned elements. Master this concept and you'll never struggle with layering issues again β from modals to tooltips to dropdowns. π