CSS Z-index

The z-index property controls the stacking order of positioned elements. Higher z-index values appear above lower ones. This is useful when creating overlays, modals, or layered UI elements. Remember, z-index only applies to elements that have a positioned ancestor (not static).

Key Topics

  • Stacking Context
  • Positioned Elements
  • Overlays and Modals

Example

An element with z-index: 10; appears above another with z-index: 5;, if both are positioned.

.box1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 100px;
    height: 100px;
    background: red;
    z-index: 5;
}
.box2 {
    position: absolute;
    top: 70px;
    left: 70px;
    width: 100px;
    height: 100px;
    background: blue;
    z-index: 10;
}

Explanation: The blue box (z-index 10) appears on top of the red box (z-index 5) because it has a higher stacking order.

Stacking Context

Elements with certain properties (position, opacity, transform) create new stacking contexts. Z-index only applies within that context, so understanding stacking contexts is crucial for troubleshooting layering issues.

Key Takeaways

  • Layer Control: Z-index determines which element sits above another.
  • Position Required: Elements must be positioned (relative, absolute, etc.) for z-index to take effect.
  • Stacking Contexts: Complex layering may require understanding stacking contexts.