What is Stacking Context in CSS: Explained Simply
stacking context is like a special group that controls how elements are layered or stacked on top of each other. It determines which elements appear in front or behind others based on rules like z-index and certain CSS properties.How It Works
Imagine you have a stack of books on a table. Each book is like an element on a webpage. A stacking context is like a smaller stack inside the big stack, where the order of books is controlled separately from the rest.
In CSS, stacking contexts form when certain properties are applied, such as position with z-index, opacity less than 1, or transform. Elements inside one stacking context are layered relative to each other, but the entire group is layered as a single unit compared to other stacking contexts.
This means that even if an element inside a stacking context has a high z-index, it cannot appear above elements in a different stacking context that is higher in the overall page order.
Example
This example shows two boxes with different stacking contexts. The red box has a z-index of 1 and the blue box has a z-index of 2, but the blue box is inside a stacking context with opacity: 0.9. The red box appears on top because its stacking context is higher.
html, body {
height: 100%;
margin: 0;
}
.container {
position: relative;
width: 200px;
height: 200px;
margin: 50px;
}
.red-box {
position: absolute;
top: 20px;
left: 20px;
width: 150px;
height: 150px;
background-color: red;
z-index: 1;
}
.blue-box {
position: absolute;
top: 70px;
left: 70px;
width: 150px;
height: 150px;
background-color: blue;
opacity: 0.9; /* creates stacking context */
z-index: 2;
}When to Use
Use stacking contexts to control which elements appear above others, especially when dealing with overlapping content like menus, modals, or tooltips. Understanding stacking contexts helps avoid unexpected layering issues.
For example, if a dropdown menu is hidden behind other content, creating a stacking context with position and z-index can bring it to the front. Also, properties like opacity or transform can unintentionally create stacking contexts, so knowing this helps debug layering problems.
Key Points
- A stacking context is a group of elements layered together in a specific order.
- It is created by CSS properties like
positionwithz-index,opacityless than 1,transform, and others. - Elements inside a stacking context are layered relative to each other but as a whole compared to other stacking contexts.
- Understanding stacking contexts helps fix layering and overlap issues in web design.