#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 7 of 49medium

How Does z-index Work?

Understanding stacking context and z-index in CSS.

What You'll Learn

  • How z-index works
  • Stacking context
  • Common issues

What is z-index?

z-index controls the stacking order of positioned elements. Higher values appear on top.

Requirements

  • Element must have position other than static
  • Or be a flex/grid child

Example

styles.cssCSS
.behind {
  position: relative;
  z-index: 1;
}

.in-front {
  position: relative;
  z-index: 2;
}

Stacking Context

A new stacking context is created by:

styles.cssCSS
/* These create new stacking contexts */
.context {
  position: relative;
  z-index: 1; /* any value other than auto */
}

.context2 {
  opacity: 0.99; /* less than 1 */
}

.context3 {
  transform: translateX(0);
}