Skip to main content
Practice

Determining the Stacking Order with z-index

In CSS, the z-index property represents the stacking order of an HTML element and can be used to control the overlaying order of elements.

It's similar to deciding which card sits on top and which one lies beneath in a stack of cards.

The higher the z-index value, the more likely the element will appear above other elements with a lower z-index value.


Basic Rules

  • z-index only applies to elements that have a position property other than static, such as relative, absolute, or fixed.

  • The z-index takes integer values. Positive, negative, and zero values are all acceptable.

Example:

CSS
div#one {
position: absolute;
z-index: 1;
}

div#two {
position: absolute;
z-index: 2;
}

With the above setup, the div#two element will be displayed above the div#one element.


Using Negative Values

Assigning a negative value to the z-index will place the element behind other elements.

Example:

CSS
div#one {
position: relative;
z-index: -1;
}
  • The div#one element, with a z-index value of -1, will appear behind other elements.

  • By using z-index, you can freely control the overlapping order of various elements on a web page.


Follow the highlighted parts of the code to practice.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.