CSS Layout - z-index Property
- Previous Page CSS Positioning
- Next Page CSS Overflow
z-index
elective course
Course recommendation:
property specifies the stacking order of the element.
z-index
The z-index property
property specifies the stacking order of the element (which element should be in front, which element should be at the back).
The stacking order of an element can be a positive or negative number:

This is a title z-index
because the image's
instance
img { position: absolute; left: 0px; top: 0px; z-index: -1; }
Note:z-index
only applies topositioning elements(position: absolute
、position: relative
、position: fixed
or position: sticky
)andflex items(display: flex
(the direct child elements of the element).
Another z-index instance
instance
Here, we see that elements with a larger stacking order are always above elements with a smaller stacking order:
<html> <head> <style> .container { position: relative; } .black-box { position: relative; z-index: 1; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; z-index: 3; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; z-index: 2; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </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>
without z-index
If two positioning elements are not specified z-index
overlapThe last defined in the HTML codeelements will be displayed on top.
instance
Similar to the above example, but here there is no specification z-index
:
<html> <head> <style> .container { position: relative; } .black-box { position: relative; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </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>
CSS Property
Property | Description |
---|---|
z-index | Set the stacking order of elements. |
- Previous Page CSS Positioning
- Next Page CSS Overflow