CSS Z-Index - Detailed Overview

Introduction to CSS Z-Index

The CSS z-index property controls the stacking order of elements that overlap. It only works on positioned elements (i.e., elements with a position value other than static). Higher z-index values are stacked on top of lower values.

Basic Example

Here is an example of how z-index affects the stacking order of overlapping elements:

.box {
    position: relative;
    background-color: #e0e0e0;
    padding: 10px;
    border: 1px solid #ddd;
}

.overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
}

.content {
    position: relative;
    z-index: 2;
    background-color: #f0d0d0;
    padding: 20px;
    border: 1px solid #ddd;
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #d0f0d0;
    z-index: 0;
}

Multiple Overlapping Elements

Using z-index with multiple elements:

.box1 {
    position: relative;
    z-index: 1;
    background-color: #e0e0e0;
    padding: 10px;
    border: 1px solid #ddd;
}

.box2 {
    position: relative;
    z-index: 2;
    background-color: #f0d0d0;
    padding: 10px;
    border: 1px solid #ddd;
    margin-top: -50px;
}

This is box1 with z-index 1.
This is box2 with z-index 2, which overlaps box1.

Stacking Context

Each positioned element with a z-index value creates a stacking context. Elements inside the stacking context are stacked according to their z-index values relative to each other:

.parent {
    position: relative;
    z-index: 1;
    background-color: #e0e0e0;
    padding: 20px;
}

.child {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #f0d0d0;
    padding: 10px;
    z-index: 2;
}

Parent element with z-index 1.
Child element with z-index 2.