When overlapping elements start playing “who goes in front?”, use z-index. It sets an element’s place in the stacking context: a higher value appears over a lower value. Think of each element as a paper cutout; the bigger number gets placed closer to the top of the pile. section 8.7
z-index works alongside positioning. After choosing position and any top, right, bottom, or left offsets, give overlapping elements z-index values to control their layers. Positive values put an element above lower values; negative values can put a descendant below its ancestor. section 8.12 section 8.7
element {
position: static|relative|absolute|fixed|sticky;
top: measurement|percentage|auto;
right: measurement|percentage|auto;
bottom: measurement|percentage|auto;
left: measurement|percentage|auto;
z-index: integer|auto;
}
The basic positioning pattern includes z-index. Use an integer when you need a specific layer, or leave it as auto when you do not. section 8.7
PLAY: Reveal an image on hover
Place an “after” image directly over a “before” image with absolute positioning, then give the overlay z-index: 1. Starting it at opacity: 0 hides it; opacity: 1 on hover fades the top image into view. The parent uses position: relative so the overlay has the right positioning context. section 20.5
REMEMBER:
- Higher z-index values layer over smaller values when elements overlap. section 8.7
- A negative z-index can place a descendant below its ancestor in the stacking context. section 8.12
- Fixed elements can use z-index too—for example, to keep a heading or navigation layer in front. section 8.10

