This example shows three overlapping colored boxes with different z-index values. The red box is on top because it has the highest z-index. The blue box is below it, and the green box is at the bottom. This demonstrates how stacking context controls which element appears above others.
<!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>