The z-index property specifies the stack order of an element. An element with a higher z-index value is always in front of an element with a lower stack order.
Imagine your screen as a 3D space with an X, Y, and Z axis. The Z axis represents depth — how close or far an element is from the viewer. Higher numbers are "closer" to you and overlap lower numbers.
/* Z-Index logic */
.blue-box { position: absolute; z-index: 1; }
.green-box { position: absolute; z-index: 5; }
.red-box { position: absolute; z-index: 10; }
Z-index only works on elements that have a position value other than static (like relative, absolute, fixed, or sticky). If an element is static, the z-index property is completely ignored.
/* Incorrect (wont work) */
div {
z-index: 10;
}
/* Correct (will work) */
div {
position: relative;
z-index: 10;
}
You can use negative values to place an element behind its parent or other elements that have a z-index of 0 or auto.
.background-layer {
position: absolute;
z-index: -1;
}
If no z-index is specified, elements follow the Natural Stacking Order. This means elements that appear later in the HTML code will naturally sit on top of elements that appeared earlier, provided they are positioned.