CSS Documentation

Z-index

CSS Z-index

The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order.

How Z-index Works

Z-index only works on elements with a position value of absolute, relative, fixed, or sticky.

.element {
position: absolute;
z-index: 1;
}

Z-index Values

  • Auto: Sets the stack order equal to its parents. This is default.
  • Number: Sets the stack order of the element. Negative numbers are allowed.
  • Initial: Sets this property to its default value.
  • Inherit: Inherits this property from its parent element.

Example

Here's an example of using z-index:

.box1 {
position: absolute;
z-index: 2;
background: red;
}

.box2 {
position: absolute;
z-index: 1;
background: blue;
}

In this example, .box1 will appear on top of .box2 because it has a higher z-index value.

Best Practices

  • Use z-index sparingly and only when necessary
  • Keep z-index values low and manageable
  • Be aware of stacking contexts
  • Use z-index with position: relative for better control
  • Avoid using !important with z-index

Understanding and properly using z-index is crucial for controlling the layout and overlap of elements in complex web designs.