Learn the concept
CSS Positioning & Stacking Context
CSS has five position values: static (default, normal flow), relative (offset from normal position), absolute (positioned relative to nearest positioned ancestor), fixed (positioned relative to viewport), and sticky (toggles between relative and fixed based on scroll position).
While modern CSS layouts often rely on Flexbox and Grid, understanding the core position property values is still crucial for specific placement needs.\n\nposition: static (default)\n- Normal document flow\n- top/right/bottom/left have no effect\n\nposition: relative\n- Stays in normal flow (space is preserved)\n- Can be offset with top/right/bottom/left\n- Creates a positioning context for absolute children\n\nposition: absolute\n- Removed from normal flow (no space preserved)\n- Positioned relative to nearest positioned ancestor (not static)\n- If no positioned ancestor, relative to the document body\n\nposition: fixed\n- Removed from normal flow\n- Positioned relative to the viewport\n- Stays in place during scrolling\n- Common for: headers, modals, floating buttons\n\nposition: sticky\n- Behaves as relative until scroll threshold, then becomes fixed\n- Must specify at least one of top/right/bottom/left\n- Common for: sticky headers, table headers
/* Relative — offset from normal position */
.badge {
position: relative;
top: -10px; /* moves up 10px from where it would be */
left: 5px;
}
/* Absolute — positioned within parent */
.card {
position: relative; /* creates positioning context */
}
.card .close-btn {
position: absolute;
top: 8px;
right: 8px;
}
/* Fixed — stays in viewport */
.floating-btn {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 100;
}
/* Sticky — sticks on scroll */
.table-header {
position: sticky;
top: 0;
background: white;
z-index: 10;
}That remains visible at the top or bottom of the viewport while the user scrolls through content.
That overlays other content and is precisely positioned relative to a trigger element or the viewport.
Where certain widgets or controls need to be absolutely positioned within a relatively positioned container for precise alignment.
Create a navigation bar that uses `position: sticky` to stay at the top of the viewport as the user scrolls.
Develop a reusable tooltip component that appears next to an element on hover using `position: absolute`.
Amazon's product pages use various positioning techniques for elements like 'Add to Cart' buttons (often sticky), image carousels, and overlaid quick-view pop-ups, ensuring a rich and interactive user experience.
Stripe's payment forms and dashboards utilize CSS positioning to create highly functional and visually clean interfaces. Elements like input field labels, validation messages, and loading spinners are precisely placed using `absolute` or `relative` positioning.