CSS Positioning
Positioning determines where elements appear on the screen and how they interact with other elements. By changing the position property, you can move elements around, fix them in place, or make them stick during scrolling.
Position Values
static→ default; elements follow normal document flow.relative→ element stays in flow but can be shifted usingtop,right,bottom,left.absolute→ element is removed from flow and positioned relative to the nearest non-static ancestor.fixed→ element is removed from flow and positioned relative to the viewport (window).sticky→ element toggles between relative and fixed depending on scroll position.
Static Positioning
Default for all elements. They appear in normal flow and ignore top, right, bottom, left.
Code Block Loading...
Relative Positioning
Element remains in flow but can be offset relative to its normal position.
Code Block Loading...
The original space is preserved, so other elements don’t collapse.
Absolute Positioning
Element is removed from flow and positioned relative to the nearest ancestor with position: relative (or the viewport if none).
Code Block Loading...
The box is pinned to the top-left of .child.
Fixed Positioning
Element is removed from flow and positioned relative to the viewport. It stays fixed even when scrolling.
Code Block Loading...
Great for sticky headers, navbars, or floating buttons.
Sticky Positioning
Element behaves like relative until a scroll threshold, then sticks like fixed.
Code Block Loading...
Useful for sticky table headers or section labels.
Interactive Playground
Key Takeaways
- Static → default, follows normal flow.
- Relative → moves element but preserves space.
- Absolute → removes element from flow, positioned relative to nearest non-static ancestor.
- Fixed → pinned to viewport, unaffected by scroll.
- Sticky → hybrid between relative and fixed, sticks during scroll.