CSS Z-index
The CSS z-index
property controls the stacking order of positioned elements on a web page. It determines which elements should be positioned in front or behind other elements. The higher the z-index
value, the closer the element is to the viewer.
Here is an overview of how the z-index
property works:
z-index
only applies to elements with aposition
value ofrelative
,absolute
, orfixed
. Elements with astatic
position (the default) are unaffected byz-index
.- Elements with a higher
z-index
value will appear in front of elements with a lower value. If two elements have the samez-index
, the one appearing later in the HTML markup will be on top. - Negative
z-index
values are allowed. Elements with a negativez-index
will be positioned behind elements with a positive value or elements with the defaultz-index
of 0. z-index
is relative to the stacking context. Each positioned element creates a new stacking context, which means thez-index
of an element is only compared to other elements within the same stacking context. Elements in different stacking contexts are completely independent of each other.- Stacking contexts are created by elements with a
position
value other thanstatic
, and also by elements with atransform
,opacity
,filter
, orwill-change
property set to anything other thannone
. - Stacking contexts can be nested. A child element with a higher
z-index
within a parent stacking context will be positioned above other siblings within the same parent stacking context. - In a document tree, the root element (usually
<html>
) forms the initial stacking context with a defaultz-index
of 0. This means elements positioned within the root element will be stacked in relation to each other.
It’s important to note that the z-index
property only affects elements that have overlapping content. If elements are not overlapping, the z-index
value has no effect.
Here’s an example of how the z-index
property can be used:
css
.container {
position: relative;
}
.element-1 {
position: absolute;
z-index: 2;
}
.element-2 {
position: absolute;
z-index: 1;
}
In this example, element-1
will appear in front of element-2
because it has a higher z-index
value.
Remember to use z-index
with caution as it can sometimes lead to unexpected results or conflicts.