Z-Index and Stacking Contexts
What Is It?
z-index controls stacking within a stacking context. A child cannot escape its parent stacking context just by using a huge number.
Properties, Tags and Attributes Explained
z-index: Sets stack level for positioned elements and flex or grid items.isolation: isolate: Creates a local stacking context.transform / opacity: A non-none transform or opacity below 1 can also create a stacking context.
Each example is a complete HTML page. The CSS is inside the head's style element. Use Try in new tab to edit the CSS or HTML, run your changes, and reset the example.
Example 1: Overlapping boxes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Z-Index and Stacking Contexts</title>
<style>
.stage { position: relative; height: 140px; isolation: isolate; }
.box { position: absolute; padding: 24px; }
.back { background: #bfdbfe; left: 10px; top: 10px; z-index: 1; }
.front { background: #fde68a; left: 70px; top: 45px; z-index: 2; }
</style>
</head>
<body>
<div class="stage"><div class="box back">Back</div><div class="box front">Front</div></div>
</body>
</html>Browser preview
What you see: The yellow box with stack level 2 paints above the blue box.
Example 2: Local badge layer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Z-Index and Stacking Contexts</title>
<style>
.card { position: relative; isolation: isolate; background: #e2e8f0; padding: 24px; }
.badge { position: absolute; right: 4px; top: 4px; z-index: 1; background: #bbf7d0; }
</style>
</head>
<body>
<div class="card"><span class="badge">Featured</span><p>A locally layered component</p></div>
</body>
</html>Browser preview
What you see: The badge layers within the isolated card.
When and Where to Use It
Use local stacking contexts for layered components and a small documented set of layer values for menus or overlays.
Common Mistake or Useful Tip
If z-index seems ineffective, inspect ancestor stacking contexts in DevTools before increasing the number.
Try It Yourself
Swap the first example z-index values.