Preloader

Z Index

Free CSS Developer Roadmap 2026 CSS roadmap for beginners Learn CSS step by step roadmap Responsive CSS learning path
A complete FREE CSS Developer Roadmap to master layouts, responsiveness, and animations.

CSS .z-index property determines the stacking level of positioned overlapping elements. Think of it as the “z-depth” of your web page (toward your direction).

The z-index is a CSS positioning property that defines the order of “nested” elements on the z-axis in the world of web design. It implies which element would be seen more “closer”. Moreover, it requires the element‘s position property to be defined (as none of the other value (constants) would affect the z-index), this is the relative, the absolute or the fixed position. The higher the value, the nearer:

1. The Core Concept

HTML elements normally exist on the page in z-index order, with elements lower down overriding elements higher up, unless you specify otherwise.

  • Higher values move elements closer to the viewer (top).
  • Lower/Negative values move elements further away (bottom).

2. The Golden Rule: Position

The property z-index will only work on elements that have a position other than by default (static). The only way z-index will work is if you set the property to:

  • relative
  • absolute
  • fixed
  • sticky

Note: It also works on flex items or grid items, even if they are position: static.

3. How the Values Work

ValueDescription
autoDefault. Sets the stack order equal to its parent.
numberPositive or negative integers (e.g., 1, 100, -5).
initialSets the property to its default value.

Simple Example

Imagine two boxes. Even if Box 1 comes first in your HTML, you can make it sit on top of Box 2:

CSS

.box-1 {
  position: relative;
  z-index: 2; /* This stays on top */
  background: red;
}

.box-2 {
  position: relative;
  z-index: 1; /* This stays behind */
  background: blue;
  margin-top: -20px; /* Force them to overlap */
}

4. Stacking Context (The “Group” Rule)

This is where most people get frustrated. Think of a Stacking Context like a folder.

  • If “Folder A” has a z-index of 1.
  • And “Folder B” has a z-index of 2.
  • No matter how high you set the z-index of an item inside Folder A, it will never appear above Folder B.

5. Common Pitfalls

  • Forgotten Position: You set z-index: 9999 but forgot to set position: relative.
  • Parent Limitations: An element is trapped behind another because its parent has a lower z-index than the other element’s parent.
  • Opacity/Filters: Setting opacity (less than 1) or filter on an element can unexpectedly create a new stacking context.

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *