CSS Z-Index

z-index controls the stack order of elements along the z-axis (which element appears “on top”).

Only elements with a position value other than static can use z-index.

1) Basic Stacking Order


.blue  { z-index: 1; }
.red   { z-index: 2; }
.green { z-index: 3; }
z:1
z:2
z:3

Higher z-index = on top.

2) Negative z-index


.behind { z-index: -1; }
z:-1 (behind)
z:1

3) Stacking Contexts


.parent { transform: translateZ(0); } /* new context */
.child  { z-index: 999; } /* limited inside parent */
Parent (new stacking context)
child z:999
outside z:2

Even with z:999, the child cannot overlap the outside element because it’s trapped in its parent’s stacking context.

Tips for using z-index:

  • Default stacking follows DOM order when z-index is not specified.
  • Negative z-index places elements behind their parent’s background.
  • New stacking contexts are created by position with z-index, opacity < 1, transform, filter, etc.
  • Avoid arbitrary high values; manage contexts instead.