CSS z-index

When elements overlap, z-index decides which one is on top. An element with a bigger z-index is shown over elements with a smaller one.

.red   { position: absolute; left: 0;    top: 0;    z-index: 1; }
.green { position: absolute; left: 30px; top: 30px; z-index: 2; }
.blue  { position: absolute; left: 60px; top: 60px; z-index: 3; }
z-index 1, 2 and 3
1
2
3


Rules

  • z-index works only on positioned elements (relative, absolute, fixed, sticky) and on flex or grid items.
  • It can be negative, to push an element behind others.
  • If two elements have the same value, the one later in the HTML is on top.

Stacking context

A parent that has position with a z-index, or opacity less than 1, or a transform, starts a new stacking context. Its children are stacked only inside that parent, so a child with z-index: 9999 can still stay below an element outside the parent.

Note: Do not fight with huge numbers like 99999. Keep a small scale (like 10, 20, 30) for dropdowns, modals and tooltips, and write it down.

Summary

  • Bigger z-index means nearer to the visitor.
  • It needs a position (or a flex/grid item).
  • Stacking contexts limit how far a z-index can reach.
  • Next: CSS Float and Clear.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.