Retour au cours

Lesson 49: Stacking Context and Z-Index

**La Maîtrise de CSS : De zéro à expert en 100 leçons** *(Alternative, slightly punchier version using a common French idiomatic structure for full coverage: CSS : Maîtrisez l'essentiel en 100 leçons, but the first option is closer to the original progression.)*

49. Stacking Context and Z-Index

When elements overlap due to positioning (relative, absolute, fixed, sticky), z-index determines which element appears on top (closer to the user).

The Z-Index Property

  • z-index takes an integer (positive, negative, or zero).
  • Elements with a higher z-index stack on top of elements with a lower z-index.

css .background-layer { position: absolute; z-index: 1; }

.overlay-menu { position: fixed; z-index: 1000; /* This ensures the menu is almost always on top */ }

The Crucial Rule: Creating a Stacking Context

z-index only works if the element is positioned (relative, absolute, fixed, or sticky). Furthermore, z-index only compares elements within the same stacking context.

A Stacking Context is created by:

  1. The root element (<html>).
  2. An element with a position value other than static AND a z-index value other than auto (e.g., position: relative; z-index: 1;).
  3. New contexts are also created by Flexbox/Grid items and certain opacity/transform properties.

The Problem: If Element A is in context 1 (z-index: 10) and Element B is in context 2 (z-index: 1), Element B might still appear above Element A if Context 2 itself is stacked higher than Context 1.