The z-index property specifies the stack order of an element.


The z-index Property

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

Example

img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

Note: z-index only works on (position: absolute, position: relative, position: fixed, or position: sticky) and (elements that are direct children of display: flex elements).



Another z-index Example

Example

Here we see that an element with greater stack order is always above an element with a lower stack order:

 
Black box

 
Gray box

 
Green box





Without z-index

If two positioned elements overlap each other without a z-index specified, the element defined last in the HTML code will be shown on top.

Example

Same example as above, but here with no z-index specified:



 
Black box

 
Gray box

 
Green box





Test Yourself With Exercises

Exercise:

Both the header and the paragraph are positioned at the top of the page.

Make sure that the header is placed on top of the paragraph.

  

 CSS Property

Property Description
Sets the stack order of an element

CSS Z-index

Login
ADS CODE