Stacking Order Within a Context
What you'll learn: How CSS determines which elements appear on top when they overlap within the same stacking context.
When multiple elements occupy the same space inside a stacking context, the browser needs rules to decide who wins the "front row" seat. Even without explicitly setting z-index, CSS follows a specific seven-layer painting order from back to front:
The Seven-Layer Stack
Think of painting a scene on canvas—you start with the background and add layers:
- Background and borders of the stacking context element itself (the "canvas")
- Negative
z-indexchildren (positioned elements withz-index: -1,-2, etc.) - Block-level boxes in normal flow (your regular
<div>elements) - Floated elements (float left/right boxes)
- Inline and inline-block elements in normal flow (text and inline content)
- Positioned elements with
z-index: 0orz-index: auto - Positive
z-indexchildren (positioned elements withz-index: 1,2, etc.)
This order explains why text typically appears above background images, or why a positioned element with no z-index still sits above static block elements. Within each layer, elements are painted in source order (later in the HTML = on top).
Why This Matters
Understanding this order prevents surprises. You might wonder why your position: absolute element appears behind text—it's because if both have z-index: auto, inline content (layer 5) naturally paints after positioned auto elements would, but positioned elements default to layer 6, so they're typically above. The key is knowing these implicit rules before you start adding z-index values.
Key Takeaway: Even without z-index, CSS paints elements in a predictable seven-layer order within each stacking context—from backgrounds through negative z-index, blocks, floats, inlines, to positioned elements and positive z-index.