What is Z-Index?
The z-index property controls the vertical stacking order of positioned elements (which element appears on top).
Basic Example
Higher Value = On Top
Elements with higher z-index values appear above elements with lower values.
Position Requirement
z-index works only on positioned elements (position: relative, absolute, fixed, sticky).
Default Stacking
Without z-index, elements stack based on their order in the HTML (later elements appear on top).
Negative Z-Index
Stacking Context
A stacking context is formed when an element has a position and z-index, isolating its children from other elements.
Example
Common Use Cases
- Modals and popups
- Dropdown menus
- Tooltips
- Fixed headers and overlays
Best Practices
- Use minimal z-index values
- Maintain a z-index scale (e.g., 1–10–100)
- Avoid excessive stacking levels
- Understand stacking context before debugging
Common Mistakes
- Using z-index without position
- Confusion due to stacking context
- Overusing large values (9999)
- Unexpected overlap issues
Conclusion
CSS z-index controls element layering. Understanding positioning and stacking context is key to mastering it.