HTML & CSS Interview Question #83
What is z-index and when does it work?
CSS Layout, Display, Positioning, Flexbox & Grid Mid-Level Intermediate
Quick Interview Answer
z-index controls the stacking level of positioned elements and certain other layout items within stacking contexts. A larger z-index does not automatically place an element above every element on the page because stacking contexts create independent stacking hierarchies.
Detailed Explanation
z-index controls the stacking level of positioned elements and certain other layout items within stacking contexts. A larger z-index does not automatically place an element above every element on the page because stacking contexts create independent stacking hierarchies.
When z-index appears not to work, inspect whether the competing elements belong to different stacking contexts and which ancestor stacking context is above the other.
Code Example
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 1000;
}
.modal {
position: fixed;
z-index: 1010;
}