Sub topic 3
Overlapping Elements and z-index
Assume you know basic HTML, CSS selectors, the box model, and px, %, and rem. This chapter focuses on paint order: which overlapping element appears on top.
Overlapping elements and `z-index`
Positioned elements can overlap. The z-index property controls their order when they share a stacking context. A larger value is painted above a smaller value.
<div class="a">A</div>
<div class="b">B</div>
<style>
.a, .b {
position: absolute;
width: 100px;
height: 100px;
}
.a { top: 0; left: 0; background: tomato; z-index: 2; }
.b { top: 50px; left: 50px; background: steelblue; z-index: 1; }
</style>The boxes overlap, but A appears above B.
Stacking contexts and why `z-index` sometimes fails
A stacking context is an isolated paint-order group. A child cannot escape its parent stacking context, even with a very large z-index.
Common stacking-context creators include:
- A positioned element with a non-
autoz-index position: fixedorstickyopacitybelow1transformvalues other thannone
Common patterns
A corner badge uses a positioned ancestor:
.card { position: relative; }
.badge { position: absolute; top: 0; right: 0; }A sticky header needs an inset and a scrolling range:
.site-header {
position: sticky;
top: 0;
z-index: 10;
background: white;
}A modal usually places the backdrop and dialog in a deliberate order:
.backdrop { position: fixed; inset: 0; z-index: 100; }
.modal { position: fixed; z-index: 101; }Pitfalls and tool choice
If sticky positioning fails, check for an ancestor with an unexpected overflow value and ensure the parent has enough scrollable height. If an absolute element is misplaced, find its nearest positioned ancestor.
Use positioning for overlays, badges, and deliberate offsets. Use Flexbox for one-dimensional alignment, such as a row of buttons. Use Grid for two-dimensional page or card layouts. Do not use absolute positioning to replace normal layout.
Exercise
A modal has z-index: 100, but it appears below a transformed header with z-index: 1. What should you inspect?
Show answer
Inspect their ancestor stacking contexts. The modal cannot escape its parent context, so raise the parent context or restructure the overlay.