CSS - Position & Z-Index

Overview

Estimated time: 15–20 minutes

Positioning lets you offset elements and create overlays. Understand stacking contexts to control paint order.

Learning Objectives

  • Use position: relative|absolute|fixed|sticky with offsets.
  • Diagnose stacking context issues with z-index.

Details & Examples

.badge {
  position: absolute; top: .5rem; right: .5rem;
}
.sticky-bar {
  position: sticky; top: 0; z-index: 10; /* sits above content */
}
.overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,.5);
}

Try it

Common Pitfalls

  • Transforms (transform) create a new stacking context affecting z-index.
  • Unpositioned ancestors can change expected absolute positioning.

Checks for Understanding

  1. Which properties create new stacking contexts?
Show answers
  1. position: fixed, certain transforms/filters/opacity, isolation, and others per spec.

Exercises

  1. Create a sticky header that remains visible under scroll with appropriate z-index.
  2. Position an absolute badge in the top-right of a relatively positioned card.
Suggested answers
  1. position: sticky; top: 0; z-index: 10;
  2. Parent: position: relative; Badge: position:absolute; top:.5rem; right:.5rem;