The z-index
of an HTML element is a property that indicates the layer the element is placed in, in the z-axis. z-axis is the axis that goes into and out of the screen.
It is used to set the z-order of the element, in a possible scenario where elements can be stacked in layers across the z-axis.
Default Stacking Order
When z-index
for an element is not specified, the stacking order of elements is formed from back to front like this:
- The background and borders of the root element.
- Descendant, non-positioned (or static) elements, following the order of appearance in the document.
- Descendant positioned elements (or non-static), following the order of appearance in the document.
We can customize the stacking order of an element with an integer value for z-index
. A higher value brings the element closer to the front and a lower value sends it to back layers.
Stacking Context
A stacking context is a region where an element is placed in a layer computed from the value of its z-index
. Its children become enclosed within that layer. Any stacking order to be formed inside itself are contained within this stacking context. In other words, descendants of a stacking context are isolated and do not interact with those from neighboring ones.
There are many instances when a stacking context is formed.
Common examples include:
- Elements with position value of absolute or relative and have an integer z-index value.
- Elements with position value of fixed or sticky.
- Children inside flex containers, having an integer z-index.
- Children inside grid containers, having an integer z-index.
References
Top comments (0)