What is the z-index property in CSS?
Overview
In CSS, the z-index property specifies how elements stack on each other.
When elements overlap, the element with a larger z-index covers those with a smaller one.
Note: The
z-indexis usually useful with thepositionproperty (other thanposition).
Syntax
The z-index property is specified like the other CSS properties. We specify the property and its value.
property: value
Keyword value
z-index:auto;
We use the keyword value to set the context to 0. The box doesn’t establish a new local stacking context.
Using an integer
z-index: 0;
z-index: 5;
z-index: 139;
z-index: -3;
The element with a larger value covers those with smaller values.
Global values
z-index: inherit;
z-index: initial;
z-index: revert;
z-index: unset;
The global values function is the same for every CSS property.
Explanation
In the HTML section:
- Lines 5-7: We create two boxes with classes,
red-boxandblack-box.
In the CSS section:
-
Lines 4-12: These contain the CSS properties of the
red-box. -
Lines 5-7:
red-boxgets its position properties. -
Lines 8-10: We set the color, width, and height of
red-box. -
Line 11: A
z-indexproperty is set forred-box. This defines whether the box will be placed above or below any other element that is in the same position. -
Lines 13–21: Contains the CSS properties of
black box. -
Lines 14–16: The
black-boxgets its position properties. -
Lines 17–19: We set the color, width, and height of
black-box. -
Line 20: A
z-indexproperty is set for the black box. This places theblack-boxon thered-boxbecause the value of thez-indexis higher.