z-index
The z-index is a CSS property that controls the stacking order of elements that overlap on a page. An element with a higher z-index appears in front of one with a lower value. It answers a simple question: when two things sit on top of each other, which one is visible?
How stacking works
z-index only applies to positioned elements (those with a position other than static) and to flex or grid children. Values can be positive or negative, and the browser paints higher values on top.
.modal { position: fixed; z-index: 1000; }- Without a z-index, elements paint in the order they appear in the HTML.
The painting order
The browser paints in layers: first backgrounds, then non-positioned blocks, then floats, then positioned elements ordered by z-index. When two elements share the same z-index, the one later in the HTML wins.
Stacking contexts
A stacking context is a group of layers that stack together as a unit. Several properties silently create one, which is the usual source of confusion.
| Trigger | Example |
|---|---|
| Positioned element with z-index | position: relative; z-index: 1 |
| Opacity below 1 | opacity: 0.9 |
| Transform | transform: translateZ(0) |
| Filter | filter: blur(2px) |
| will-change | will-change: transform |
Why z-index fails
Most problems come from a missing position or from a parent that created a stacking context and trapped the child inside it. A z-index of 9999 cannot escape its parent's context, so it still sits behind a sibling of that parent with a higher value. Inside a context, child z-index values are only compared with each other.
Best practices
- Only add z-index where elements actually overlap.
- Use a small, documented scale (for example 10, 100, 1000) instead of arbitrary large numbers.
- Keep track of which components create a stacking context (transforms, opacity, filters), so surprises are easy to diagnose.
z-index at BeBranded
At BeBranded we keep stacking predictable with a clear layering scale, so menus, modals and sticky bars never fight each other. It is part of the tidy, maintainable front-end we deliver through our design work.