What is `z-index` and how does stacking context work

The z-index CSS property controls the vertical stacking order of elements that overlap. An element with a higher z-index is positioned in front of an element with a lower z-index. This property only works on positioned elements (elements whose position value is set as anything other than "static").

To understand z-index, it is important to grasp the concept of stacking context. A stacking context is formed by an element that has a position value other than "static" and a z-index value other than "auto". Within this context, elements will be layered relative to each other. Child elements of a stacking context will respect their parent's stacking order.

For example:

<div style="position: relative; z-index: 1;"> Layer 1 - Background <div style="position: absolute; z-index: 2;"> Layer 2 - Middle </div> <div style="position: absolute; z-index: 3;"> Layer 3 - Foreground </div> </div>

z-index stacking context CSS positioning layering