CSS Z-Index

What Is Z-Index?

The z-index property in CSS controls the stacking order of elements along the z-axis — the imaginary line perpendicular to the screen (front-to-back). This determines which elements appear in front of others when they overlap.

Key points to know:

  • A higher z-index value means the element will appear in front of elements with lower values.
  • The default z-index is auto, which follows the element's natural HTML order.
  • z-index only works on elements with a positioning context (position: relative, absolute, fixed, or sticky).
  • If two elements have the same z-index, their stacking order depends on their position in the DOM (elements later in the HTML appear on top).

When Z-Index Applies

Important: z-index only works on elements with a position of relative, absolute, fixed, or sticky.

.box1 {
  position: absolute;
  z-index: 1;
}
.box2 {
  position: absolute;
  z-index: 2;
}

Positive, Negative, and Auto Values

  • z-index: 10 – appears above elements with lower index
  • z-index: -1 – pushes element behind others
  • z-index: auto – default stacking context

Default Stacking Order

If no z-index is set, elements are layered based on their HTML order and positioning. Positioned elements are stacked above static ones by default.

Layering Multiple Items

Use z-index to stack tooltips, modals, navigation bars, dropdowns, etc.

.modal {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
}

Practice Prompt

Create three overlapping boxes with different z-index values:

<div style={{
  position: "absolute",
  top: "50px",
  left: "50px",
  width: "150px",
  height: "150px",
  backgroundColor: "lightblue",
  zIndex: 1
}}>
  Box 1 (z-index: 1)
</div>

<div style={{
  position: "absolute",
  top: "100px",
  left: "100px",
  width: "150px",
  height: "150px",
  backgroundColor: "salmon",
  zIndex: 3
}}>
  Box 2 (z-index: 3)
</div>

<div style={{
  position: "absolute",
  top: "75px",
  left: "75px",
  width: "150px",
  height: "150px",
  backgroundColor: "palegreen",
  zIndex: 2
}}>
  Box 3 (z-index: 2)
</div>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic