Z-Index and Stacking Context
The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. However, z-index only works on positioned elements (position: absolute, relative, fixed, or sticky) and flex items.
1. The z-index Property
- Values: Integer (positive, negative, or zero).
autois the default. - Behavior: Higher numbers are closer to the user (on top). Lower numbers are further away (behind).
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1; /* Behind other content */
}
2. Stacking Context
A common confusion is when an element with z-index: 999 is still behind an element with z-index: 1. This happens because of Stacking Contexts.
A stacking context is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user.
How a Stacking Context is Formed
A new stacking context is formed by any element that meets specific criteria, including:
- It is the root element (
<html>). - It has a
positionvalue other thanstaticand az-indexvalue other thanauto. - It has a
positionvalue offixedorsticky. - It is a child of a flex container, with
z-indexvalue other thanauto. - It is a child of a grid container, with
z-indexvalue other thanauto. - It has an
opacityvalue less than 1. - It has a
transform,filter,perspective,clip-path,mask/mask-image/mask-bordervalue other thannone. - It has
isolation: isolate.
The Rules of Stacking
- Within a Stacking Context: Elements are stacked according to their
z-index. - Between Stacking Contexts: Stacking contexts are atomic. If Element A creates a stacking context, all of its children are confined within that context.
- If Context A is below Context B, no child of A can ever be above any child of B, regardless of how high their
z-indexis.
- If Context A is below Context B, no child of A can ever be above any child of B, regardless of how high their
Example
<div id="div1" style="position: relative; z-index: 1;">
<div id="child1" style="position: absolute; z-index: 999;">I am Child 1</div>
</div>
<div id="div2" style="position: relative; z-index: 2;">
<div id="child2" style="position: absolute; z-index: 1;">I am Child 2</div>
</div>
Result: child2 will be on top of child1.
div1hasz-index: 1.div2hasz-index: 2.- Therefore,
div2(and all its contents) is on top ofdiv1. child1'sz-index: 999is only relevant insidediv1. It cannot break out to beatdiv2.
3. isolation: isolate
The isolation property defines whether an element must create a new stacking context.
auto: Default.isolate: Forces the element to create a new stacking context.
This is useful when you want to ensure an element's children don't interact with the z-ordering of elements outside their parent, without needing to set position or z-index.
.container {
isolation: isolate;
}
programming/css/css programming/css/positioning programming/css/flexbox programming/css/grid-layout