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
The two non-obvious rules
z-indexonly works on positioned elements (anything withpositionother thanstatic).z-indexis local to its stacking context. A child withz-index: 9999can't escape a parent that creates a new stacking context with a lower z-index.
Things that create a new stacking context
| Trigger | Example |
|---|---|
| Positioned element with a numeric z-index | position: relative; z-index: 0; |
| Opacity less than 1 | opacity: 0.99 |
| Transform, filter, will-change | transform: translateZ(0) |
| isolation | isolation: 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 »</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; }
z-index only works on positioned elements.
Discussion
Loading…