Positioning
static, relative, absolute, fixed, sticky
Skills taught: css.positioning, css.z-index, css.stacking
The five position values
/* STATIC (default) — normal flow, top/right/bottom/left have no effect */
.normal { position: static; }
/* RELATIVE — stays in flow, offset from its natural position */
.shifted {
position: relative;
top: 10px; /* moves DOWN 10px from where it would normally be */
left: 20px;
}
/* ABSOLUTE — removed from flow, placed relative to nearest positioned ancestor */
.tooltip {
position: absolute;
top: 0;
right: 0; /* top-right corner of containing block */
}
/* FIXED — removed from flow, placed relative to VIEWPORT — stays while scrolling */
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
}
/* STICKY — in flow until threshold, then fixed */
.sticky-nav {
position: sticky;
top: 0; /* sticks when it reaches 0px from top of viewport */
z-index: 50;
}
Containing block — the anchor for absolute
/* Pattern: position: relative on parent, absolute on child */
.card {
position: relative; /* makes this the containing block */
}
.card .badge {
position: absolute;
top: 12px;
right: 12px; /* top-right corner of .card, not the page */
}
/* Without position: relative on .card,
.badge would be positioned relative to the nearest
positioned ancestor — possibly the entire page */
z-index — stacking order
/* Higher z-index = closer to the viewer */
.modal-overlay { position: fixed; z-index: 300; }
.modal { position: fixed; z-index: 400; }
.tooltip { position: absolute; z-index: 200; }
.header { position: fixed; z-index: 100; }
/* z-index only works on POSITIONED elements (not static) */
.div-no-position { z-index: 999; } /* has NO effect */
Warning: A common z-index mistake: setting z-index on a non-positioned element (position: static) has no effect. The element must have position set to anything other than static.
Frequently Asked Questions
What is the difference between fixed and sticky?
fixed is always relative to the viewport — it never moves. sticky starts in normal flow (like relative) and only sticks when scrolled to the specified threshold (top: 0). A sticky element is constrained to its scroll container; fixed is not.
Why doesn't my z-index work?
Two common reasons: (1) the element has position: static — z-index only works on positioned elements. (2) A parent creates a stacking context with a lower z-index — children cannot escape their parent's stacking layer.