CSS Z-Index
Control stacking order and diagnose overlapping interface layers.
The CSS z-index property controls which element appears in front when two or more elements overlap.
Imagine several sheets of paper placed on a table. The sheet on top covers the sheets below it. The z-index property creates a similar stacking order for webpage elements.
.box {
position: relative;
z-index: 2;
}An element with a higher z-index usually appears in front of an element with a lower value.
How Z-Index Works
Consider two overlapping boxes:
.blue-box {
position: absolute;
z-index: 1;
}
.orange-box {
position: absolute;
z-index: 2;
}The orange box appears above the blue box because 2 is greater than 1.
The value does not require a unit:
.card {
z-index: 5; /* Correct */
}Do not write 5px because z-index accepts integer values, not length values.
Z-Index and Positioned Elements
The z-index property commonly works with elements using:
- position: relative
- position: absolute
- position: fixed
- position: sticky
.modal {
position: fixed;
z-index: 100;
}It can also affect Flexbox and Grid children even when they do not have a special position value.
If z-index appears to have no effect, first check the element's position property and its parent elements.
Common Z-Index Values
z-index accepts different types of values:
.first {
z-index: 3;
}
.second {
z-index: 0;
}
.third {
z-index: -1;
}
.fourth {
z-index: auto;
}- A positive value can place an element in front.
- 0 places it in the current stacking level.
- A negative value can move it behind other elements.
- auto uses the normal stacking order.
Avoid extremely large values such as 999999. A simple, organized range is easier to manage.