When elements are positioned, they may overlap with other elements.
The z-index property dictates the stacking order of an element, determining whether it should be placed in front of or behind other elements.
The stack order of an element can be positive or negative:
Example
img { position: absolute; left: 0px; top: 0px; z-index: -1; } |
Note: The z-index property exclusively affects positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements).
Example
Here we observe that an element with a higher stack order consistently appears above an element with a lower stack order:
<html> <head> <style> .container { position: relative; } .black-box { .gray-box { .green-box { </head> <body> <div class=”container”> <div class=”black-box”>Black box</div> <div class=”gray-box”>Gray box</div> <div class=”green-box”>Green box</div> </div> </body> </html> |
When two positioned elements overlap each other and no z-index is specified, the element declared later in the HTML code will be displayed on top.
Example
In the same example as previously mentioned, but in this case, no z-index is specified:
<html> .black-box { .gray-box { .green-box { |
Property |
Description |
z-index |
Specifies the stacking order of an element. |