Introduction
Stacking context helps decide which elements appear on top when they overlap on a webpage.
Jump into concepts and practice - no test required
/* Create a stacking context by setting position and z-index */ .selector { position: relative; /* or absolute, fixed, sticky */ z-index: 10; /* any integer value */ }
.box1 { position: relative; z-index: 1; } .box2 { position: relative; z-index: 2; }
.container { opacity: 0.9; } .child { position: absolute; z-index: 5; }
.empty { /* No stacking context because no position or z-index */ } .single { position: static; z-index: 10; /* ignored because position is static */ }
.fixed { position: fixed; z-index: 100; } .absolute { position: absolute; z-index: 50; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Stacking Context Example</title> <style> body { margin: 2rem; font-family: Arial, sans-serif; } .box1 { position: relative; z-index: 1; width: 10rem; height: 10rem; background-color: lightblue; border: 2px solid blue; padding: 1rem; } .box2 { position: relative; z-index: 2; width: 10rem; height: 10rem; background-color: lightcoral; border: 2px solid red; margin-top: -6rem; margin-left: 4rem; padding: 1rem; } .box3 { position: relative; z-index: 0; width: 10rem; height: 10rem; background-color: lightgreen; border: 2px solid green; margin-top: -6rem; margin-left: 8rem; padding: 1rem; } </style> </head> <body> <h1>Stacking Context Demo</h1> <p>Boxes overlap. The red box (z-index: 2) appears on top, then blue (z-index: 1), then green (z-index: 0).</p> <div class="box1">Blue box (z-index: 1)</div> <div class="box2">Red box (z-index: 2)</div> <div class="box3">Green box (z-index: 0)</div> </body> </html>
position: relative and z-index set mentions position: relative with z-index, which creates a stacking context. Other options do not create stacking contexts.position: relative and z-index set -> Option Bposition: relative and z-index: 5, which correctly creates a stacking context. Others either have static position or irrelevant properties.<div class='parent'>
<div class='child1'>Child 1</div>
<div class='child2'>Child 2</div>
</div>
.parent { position: relative; z-index: 1; }
.child1 { position: absolute; z-index: 2; }
.child2 { position: absolute; z-index: 1; }position: relative and z-index: 1, creating a stacking context. Children stack inside this context.z-index: 2, child 2 has z-index: 1. Higher z-index means it appears on top..box { position: absolute; }z-index is set.position: absolute but no z-index, so no stacking context is created.z-index property -> Option A<div class='outer'> <div class='inner'>Content</div> </div>
.outer { position: relative; z-index: 1; }
.inner { position: relative; z-index: 10; }position: relative and z-index: 1. The inner element creates a new stacking context inside outer with position: relative and z-index: 10.