Home
 › Learn
 › CSS

CSS Z-index

CSS: Learn about css Z-index

Updated At: November 2024
CSS Z-index

The CSS z-index property is effectively used to define the stacking order of elements.

CSS Z index property

⁠⁠Below is the syntax for adding z-index:

Selector {
  z-index: value;
}⁠
  • The selector can be any one or more of those discussed previously in CSS Selectors.

  • " z-index" is the property key

  • " value" can be any number.

⁠⁠

In the previous article, we learned about CSS position. In that example, when you scroll, observe that the relative positioned and absolute positioned elements hide the sticky positioned element.

css_12_01.png



⁠⁠What do we need to do to make the sticky-positioned element always fully visible ? ⁠⁠The answer is the z-index property.

In the same playground, add the z-index property in the sticky class like below:

.sticky {
  position: sticky;
  top: 0;
  z-index: 1;   // add this
}


⁠If you scroll now, the sticky-positioned element will always be fully visible.

css_12_02.png


⁠With the help of z-index, we can change the order of elements in the stack. Try adding z-index to other elements and observe the various differences.

Notes:

  • The stacking order of positioned elements can be influenced by factors like the position property value (static, relative, absolute, fixed, or sticky), negative z-index values, and the rendering order.
  • 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.
  • The z-index property accepts integer values, with higher numbers indicating that the element should be placed on top of elements with lower z-index values.
  • The z-index property in CSS only controls the stacking order of positioned and flexbox-related elements.


⁠Want to practice more?
Click here for more hands-on exercise.

⁠⁠References:

JavaScript

    React

      NextJS

        HTML

          CSS

            Sign up for our newsletter.

            Copyright © theHardCoder 2023 - 2025