HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Z-Index

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.


The Stacking Concept

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: 1
z: 5
z: 10
/* Z-Index logic */
.blue-box  { position: absolute; z-index: 1; }
.green-box { position: absolute; z-index: 5; }
.red-box   { position: absolute; z-index: 10; }

Requirements for Z-Index

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;
}

Negative Z-Index

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;
}

Automatic Stacking

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.


Note: Z-index creates Stacking Contexts. If a parent has a specific z-index, its children are confined within that parent's depth level, regardless of how high their own individual z-index values are.