CSS z-index

Theory & Explanation

z-index is a CSS property that controls the vertical stacking order of positioned elements (those with position set to relative, absolute, fixed, or sticky). Elements with a higher z-index value appear in front of those with a lower value. z-index only works on elements that create a stacking context.

When to Use z-index

Best Practices

Code Examples

/* Basic z-index */
.box1 { z-index: 1; }
.box2 { z-index: 2; }

/* Stacking context */
.parent {
  position: relative;
  z-index: 10;
}
.child {
  position: absolute;
  z-index: 2;
}

Interactive Demos

Default stacking (no z-index)
Box 1
Box 2
Box 3
Later elements appear on top by default.
z-index stacking
z-index: 1
z-index: 3
z-index: 2
Box with higher z-index appears on top, regardless of HTML order.
Stacking context (nested)
Parent (z-index: 10)
Child (z-index: 2)
Outside (z-index: 5)
Child's z-index is relative to its parent stacking context, not the page.

Hover over the boxes to see their stacking visually. Try changing the z-index values in the code for different effects.

← Back to Home