CSS
What Does the z-index Property Control in CSS?
When building modern web interfaces, elements often overlap — modals pop over pages, dropdowns expand over headers, and tooltips hover near text. To manage which element appears on top, CSS provides the z-index
property.
In this article, we’ll break down:
- What the
z-index
property does - How it works with stacking order
- When and how to use it effectively
🎯 What Does z-index
Do?
The z-index
property in CSS controls the stacking order of overlapping elements. It determines which elements appear in front of or behind others on the z-axis (the imaginary third dimension perpendicular to the screen).
Simply put: higher
z-index
values appear on top of lower ones.
📌 Syntax
.element {
position: relative;
z-index: 10;
}
🔍 Important:
z-index
only works on elements with a positioning context, such as:position: relative
position: absolute
position: fixed
position: sticky
🧪 Example
Imagine a modal overlapping a background content area:
<div class="background">Page Content</div>
<div class="modal">Modal Window</div>
.background {
position: relative;
z-index: 1;
}
.modal {
position: fixed;
z-index: 1000;
}
Here, the modal will appear above the page content.
🔢 Understanding Stacking Order
The stacking order is the order in which elements are layered on top of each other along the z-axis.
z-index Value | Stacking Behavior |
---|---|
auto | Default browser order |
0 | Neutral stacking |
Positive number | Higher = in front |
Negative number | Lower = behind others |
🧱 Stacking Contexts
A stacking context is a 3D space in which elements are stacked. A new stacking context is created when:
- An element has a
position
and az-index
value - An element uses certain CSS properties like
transform
,opacity
, orfilter
This means z-index
values are only compared within the same stacking context.
⚠️ Common Pitfalls
- Missing
position
:z-index
won’t work unless the element is positioned. - Nested stacking contexts: High
z-index
on a child may not rise above elements outside its parent.
/* Won’t stack unless position is set */
.box {
z-index: 5; /* ❌ Ineffective without position */
}
✅ Best Practices
- Keep
z-index
values manageable and semantic (e.g.,z-10
,z-20
,z-50
) - Use a consistent scale (Tailwind CSS uses this approach)
- Group components logically to avoid stacking conflicts
- Be mindful of nested stacking contexts when debugging
📝 Conclusion
The z-index
property is a key CSS tool that controls which elements sit on top of others in layered interfaces. Mastering it helps you manage dropdowns, modals, tooltips, and all overlapping UI elements with precision and clarity.
🔑 Recap
Concept | Meaning |
---|---|
z-index | Controls stacking order |
Higher value | Appears in front |
Requires position | relative , absolute , etc. |
Affected by context | Must share the same stacking context |