z-index & Stacking Contexts
Z-index controls the vertical stacking order of elements. Higher z-index values appear on top. However, z-index only works on positioned elements and creates stacking contexts that can be confusing.
Z-index Basics
CSS
/* Z-index only works on positioned elements */
.element {
position: relative;
z-index: 10;
}
/* Higher values appear on top */
.layer1 {
position: absolute;
z-index: 1;
}
.layer2 {
position: absolute;
z-index: 2;
/* Appears above layer1 */
}
/* Negative values go below */
.behind {
position: relative;
z-index: -1;
}Stacking Context
CSS
/* Creating a stacking context */
/* 1. opacity < 1 creates stacking context */
.element {
opacity: 0.9;
/* Children z-index is local to this context */
}
/* 2. position with z-index (if positioned) */
.element {
position: relative;
z-index: 1;
}
/* 3. transform, filter, or other properties */
.element {
transform: translate(10px);
/* Creates stacking context */
}
/* Modal dialog setup */
.modal-backdrop {
position: fixed;
z-index: 100;
}
.modal {
position: fixed;
z-index: 101;
/* Appears above backdrop */
}Note
Z-index controls stacking order for positioned elements. Higher values appear on top. Be careful with stacking contexts—they can limit z-index effectiveness of children.
Next
Float and clear: [Float & Clear](/css/float-clear).