iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Z-index

z-index controls how positioned elements stack — which one paints on top when they overlap. Higher numbers stack above lower ones.

The stack

z-index: 1 z-index: 5 z-index: 10 — sits on top
Fig 1. The red box has the largest z-index, so it paints last (on top).

The two non-obvious rules

  • z-index only works on positioned elements (anything with position other than static).
  • z-index is local to its stacking context. A child with z-index: 9999 can't escape a parent that creates a new stacking context with a lower z-index.

Things that create a new stacking context

TriggerExample
Positioned element with a numeric z-indexposition: relative; z-index: 0;
Opacity less than 1opacity: 0.99
Transform, filter, will-changetransform: translateZ(0)
isolationisolation: isolate
Tip: Keep a small set of named layers (e.g. --z-base: 0; --z-dropdown: 10; --z-modal: 100;) instead of sprinkling random numbers across the codebase.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Z-index</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Lift this modal above everything else by giving it position relative and a higher z-index.

.modal { position: ; z-index: 100; }

Test yourself

Q1. On which kind of element does `z-index` take effect?
Q2. A child with `z-index: 9999` can still appear behind a sibling. Why?
Q3. Which property creates a new stacking context on its own?

Discussion

Loading…