47. Positioning Scheme: Fixed (Viewport Locked)
position: fixed removes the element from the normal flow, much like absolute. However, its reference point is always the viewport (the browser window), meaning it stays in the same place even when the user scrolls the page.
How Fixed Positioning Works
- Out of Flow: The element's original space is collapsed.
- Fixed to Viewport: The element is positioned relative to the browser window itself.
- Offsets Apply:
top,right,bottom, andleftposition the element relative to the viewport edges.
css .navbar-fixed { position: fixed; top: 0; /* Stays fixed to the top edge of the browser / left: 0; width: 100%; / Spans the full width of the browser */ background-color: #333; color: white; padding: 10px 0; }
Common Use Cases
- Fixed Navigation Bars: Headers that stay visible while scrolling.
- Floating Widgets: Live chat buttons, cookie consent banners, or sticky shopping carts.
Note: Fixed elements can be problematic on mobile devices, especially when the virtual keyboard pops up, sometimes requiring careful media query adjustments.