CSS ยท Chapter 19 of 44
CSS Z-Index
The z-index property controls the stacking order of positioned elements, determining which one appears in front when they overlap.
Higher z-index values appear above lower ones, but z-index only works on elements with a position other than static.
Syntax
z-index: 10;Stacking order basics
By default, later elements in the HTML stack above earlier ones. z-index overrides this, letting you control visual layering explicitly.
Stacking contexts
z-index only takes effect on positioned elements (relative, absolute, fixed, or sticky). Values can be negative to push elements behind others.
Example 1 (css)
.overlay {
position: absolute;
z-index: 100;
}
.background {
position: absolute;
z-index: 1;
}Output
The overlay appears above the background elementThe higher z-index value (100) places the overlay in front of the background (1).
Key points
- z-index controls which overlapping element appears on top.
- Higher values stack above lower values.
- z-index only works on positioned elements.
- Negative z-index values push elements further back.
๐ก Note: Mixing z-index across unrelated stacking contexts can behave unexpectedly โ keep it consistent.
