CSS Z-index
The CSS z-index
property controls the stacking order of positioned elements. Elements with a higher z-index
value will be displayed in front of elements with a lower value.
Understanding the Z-index Property
The z-index
property only affects elements that have a position
value other than static
(e.g., relative
, absolute
, fixed
, or sticky
).
Syntax
The syntax for the CSS z-index
property is:
/* Z-index Property Syntax */
selector {
position: ;
z-index: ;
}
- position: Must be set to a value other than
static
(e.g.,relative
,absolute
,fixed
, orsticky
). - z-index: An integer value. Higher values are in front of lower values. Can be positive, negative, or zero.
Examples
Example 1: Basic Z-index
/* Basic Z-index */
.layer1 {
position: absolute;
z-index: 1;
background: rgba(255, 0, 0, 0.5);
}
.layer2 {
position: absolute;
z-index: 2;
background: rgba(0, 255, 0, 0.5);
}
Layer 1
Layer 2
Example 2: Negative Z-index
/* Negative Z-index */
.background {
position: relative;
z-index: -1;
background-color: #ddd;
padding: 20px;
}
.foreground {
position: relative;
z-index: 1;
background-color: #fff;
padding: 20px;
}
Background
Foreground
Example 3: Stacking Context
/* Stacking Context */
.parent {
position: relative;
z-index: 10;
background-color: #f0f0f0;
padding: 20px;
}
.child {
position: absolute;
z-index: 20;
background-color: #ffcc00;
padding: 20px;
}
Parent Element
Child Element