CSS Z-Index

Control which elements appear on top using CSS stacking order.

What is CSS Z-Index?

CSS Z-Index controls the vertical stacking order of elements that overlap each other. Elements with a higher z-index value appear in front of elements with a lower value.

  • Works only on positioned elements
  • Controls front and back layers
  • Essential for modals, dropdowns, popups

Real-Life Example: Like stacked books — the book placed on top is visible first.

Z-Index Works With Position

Z-index works only when an element has a position value other than static.

  • position: relative
  • position: absolute
  • position: fixed
  • position: sticky

Important: Without position, z-index will NOT work.

Basic Z-Index Example

Overlapping Boxes


.box1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 150px;
    height: 150px;
    background: red;
    z-index: 1;
}

.box2 {
    position: absolute;
    top: 80px;
    left: 80px;
    width: 150px;
    height: 150px;
    background: blue;
    z-index: 2;
}

                

Since box2 has a higher z-index, it appears on top of box1.

Z-Index Values

Z-index accepts both positive and negative values.

  • Higher number → closer to user
  • Lower number → behind
  • Negative values push elements backward

Negative Z-Index


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

                

What is Stacking Context?

A stacking context is a group of elements that are stacked together. Z-index only works inside the same stacking context.

  • Created by positioned elements with z-index
  • Also created by opacity, transform, filter
  • Child elements cannot escape parent stacking context

Think Like This: A stacking context is like a container with its own layers.

Common Use Cases of Z-Index

  • Navigation dropdown menus
  • Modal popups
  • Tooltips
  • Sticky headers

Modal Example


.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
}

                

Common Z-Index Mistakes

  • Using z-index without position
  • Using very large random numbers
  • Ignoring stacking context
  • Overusing z-index everywhere

Tip: If z-index doesn’t work, check the parent element first.

Best Practices for CSS Z-Index

  • Use small, meaningful values
  • Group layers logically
  • Avoid unnecessary stacking contexts
  • Document z-index usage in large projects

Pro Tip: A clean z-index system keeps layouts predictable and bug-free.