Positioning
Control element placement with static, relative, absolute, fixed, and sticky positioning
Overview
The position property removes elements from or repositions them within normal document flow. Combined with the offset properties (top, right, bottom, left) and z-index, it lets you overlay, pin, and precisely place content. Absolutely positioned elements are placed relative to their nearest positioned ancestor.
Syntax / Usage
position: relative shifts an element from its normal spot while preserving its space. absolute removes it from flow and anchors it to the nearest ancestor whose position is not static. fixed anchors to the viewport, and sticky toggles between relative and fixed based on scroll.
.parent {
position: relative; /* establishes containing block */
}
.badge {
position: absolute;
top: -8px;
right: -8px;
z-index: 2;
}
.navbar {
position: sticky;
top: 0;
}
Examples
A notification badge pinned to a container corner:
.icon-button {
position: relative;
}
.icon-button .count {
position: absolute;
top: 0;
right: 0;
transform: translate(50%, -50%);
}
A header that sticks to the top while scrolling:
.site-header {
position: sticky;
top: 0;
background: white;
z-index: 10;
}
A full-screen modal overlay fixed to the viewport:
.overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
}
Common Mistakes
- Forgetting to set
position: relativeon the parent, soabsolutechildren anchor to the wrong ancestor - Expecting
z-indexto work onstaticelements — it only applies to positioned elements - Using
stickyinside anoverflow: hiddencontainer, which silently breaks stickiness - Assuming
fixedelements scroll with content; they stay locked to the viewport - Overlapping stacking contexts making
z-indexvalues behave unexpectedly
See Also
box-model css-transforms grid