Topic 7 of 30
Positioning
Overview
The position property removes elements from normal document flow and places them precisely. It enables tooltips, modals, sticky headers, fixed sidebars, and overlapping UI elements.
Syntax
css
position: static; /* Default: normal flow */
position: relative; /* Offset from normal position; creates stacking context */
position: absolute; /* Removed from flow; positioned relative to nearest positioned ancestor */
position: fixed; /* Stays in viewport even when scrolling */
position: sticky; /* Static until scroll threshold, then fixed */
/* Used with: top, right, bottom, left, z-index */
.tooltip {
position: absolute;
top: -40px;
left: 50%;
transform: translateX(-50%);
}Common Pitfalls
- Absolute positioning is relative to the nearest ancestor with position != static. If no ancestor, it's relative to the viewport.
- z-index only works on positioned elements (not static). A common bug is z-index not working on static elements.
- Interview tip: position:sticky requires a height on the scrolling container and top/bottom offset to work.
Real-World Example
A sticky navbar and an absolute-positioned dropdown menu:
example
css
/* Sticky header */
.navbar {
position: sticky;
top: 0;
z-index: 100;
background: #0f0f0f;
border-bottom: 1px solid #FFD700;
}
/* Dropdown positioned relative to parent */
.nav-item {
position: relative;
}
.dropdown {
position: absolute;
top: 100%; /* just below the nav-item */
left: 0;
background: #1a1a1a;
border: 1px solid #333;
border-radius: 8px;
min-width: 200px;
display: none;
}
.nav-item:hover .dropdown {
display: block;
}