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-indextakes an integer (positive, negative, or zero).- Elements with a higher
z-indexstack on top of elements with a lowerz-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:
- The root element (
<html>). - An element with a
positionvalue other thanstaticAND az-indexvalue other thanauto(e.g.,position: relative; z-index: 1;). - 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.