When designing web pages, you often deal with elements that overlap — like modals, dropdowns, sticky headers, or tooltips. But how do you control which element appears on top of others?
The answer is simple: CSS z-index
.
In this blog post, you’ll learn:
- ✅ What the
z-index
property does - 🧠 How stacking order works
- 💡 When and how to use
z-index
effectively - 🚫 Common mistakes to avoid
🧱 What is the z-index
Property?
The z-index
CSS property controls the vertical stacking order of overlapping elements along the z-axis (the axis coming “out of” the screen).
🔤 In simple terms:
Elements with a higher
z-index
value appear on top of elements with a lowerz-index
value — when they overlap.
🛠️ Syntax
selector {
position: relative; /* or absolute, fixed, sticky */
z-index: 10;
}
z-index: auto
— default; follows HTML orderz-index: [number]
— sets stacking level
⚠️
z-index
only works on elements that are positioned (relative
,absolute
,fixed
, orsticky
). If you usez-index
without settingposition
, it won’t do anything.
📐 How Does z-index
Work?
The browser renders HTML elements in stacking order. By default:
- Background and non-positioned elements
- Positioned elements (
relative
,absolute
,fixed
, orsticky
) - Elements with higher
z-index
values
🧠 Example:
<div class="box1">Box 1</div>
<div class="box2">Box 2</div>
.box1 {
position: absolute;
background: red;
z-index: 1;
}
.box2 {
position: absolute;
background: blue;
z-index: 2;
}
➡️ Result: Box 2
appears on top of Box 1
.
💡 Real-World Use Cases
Use Case | Why z-index Matters |
---|---|
Dropdown menus | Ensure they float above other UI |
Modals & popups | Appear above page content |
Tooltips | Hover tooltips over other text |
Sticky headers | Stay above scrolling content |
🚫 Common Mistakes to Avoid
❌ 1. Using z-index
Without Positioning
/* This won't work */
.element {
z-index: 10;
}
✔️ Fix: Add a positioning property like relative
or absolute
.
❌ 2. Overusing High Values
Using z-index: 99999
everywhere can cause layering conflicts. Instead, define a layering system for your project.
📦 Pro Tip: Understand Stacking Contexts
Each positioned element with a z-index
forms a new stacking context. Children cannot break out of their parent’s context, even with a higher z-index
.
✅ Summary
Property | Controls |
---|---|
z-index | The stack order of overlapping elements |
Requires | A position other than static |
Higher Value | Appears on top |
Default | auto (follows document order) |
🚀 Conclusion
The z-index
property is a powerful CSS tool that controls which elements appear above or below others when they overlap. When used properly, it helps you build polished UIs — from modals to dropdowns — with perfect layering.