CSS z-index
When elements overlap, the z-index property decides which one appears on top. Think of it as the Z-axis (depth) in 3D space: higher values are closer to the user, lower values are further away.
Key Points
- Default value:
auto→ stacking order follows HTML source order (later siblings appear above earlier ones). - Requires positioning:
z-indexonly works if the element hasposition: relative,absolute, orfixed. - Numeric values: Higher numbers appear above lower ones. Negative values push elements behind others.
- Non-consecutive values: Often used to leave “room” for future layers without recalculating everything.
Example
Code Block Loading...
.my-second-div appears above .my-first-div because it has a higher z-index.
Interactive Playground
Key Takeaways
z-indexcontrols stacking order of overlapping elements.- Works only with positioned elements (
relative,absolute,fixed). - Higher values appear on top, lower values behind.
- Negative values push elements further back.
- Use non-consecutive values to leave flexibility for future layers.