Stacking contexts and z-index
Definition and purpose
Stacking contexts group painted content into independent ordering units. A descendant with a large z-index cannot escape its parent context’s ordering.
Nested context stays behind
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b, #child { position: absolute; top: 0; left: 0; width: 100px; height: 60px; } #a { z-index: 1; } #child { z-index: 99; background: red; } #b { z-index: 2; background: blue; } </style> </head> <body> <div id="a"> <div id="child">Nested</div> </div> <div id="b">Front</div> </body></html>B is hit at the overlap despite the child’s 99.
Syntax and mental model
A relative or absolute box with non-auto z-index creates a stacking context; opacity below 1 is another trigger. Compare sibling contexts first, then their descendants. The full painting algorithm also includes backgrounds and non-positioned content.
Raise the whole context
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b, #child { position: absolute; top: 0; left: 0; width: 100px; height: 60px; } #a { z-index: 3; } #child { z-index: 1; background: red; } #b { z-index: 2; background: blue; } </style> </head> <body> <div id="a"> <div id="child">Nested</div> </div> <div id="b">Front</div> </body></html>The parent context is above B.
Common mistakes
Increasing a child’s z-index may not fix overlap. Inspect ancestor contexts and use meaningful local layer scales rather than arbitrary huge numbers.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Fixed and sticky positioning. Next lesson: Top layer and transformed ancestors.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stacking contexts and z-index — knowledge check
Five questions on stacking contexts and z-index.
What should be compared first for nested contexts?
Which creates a stacking context?
Can opacity below 1 create a context?
A at z-index 1 contains a child at 99; sibling B at 2. Which is above?
What is a useful debugging first step?