Retour au cours

Lesson 47: Positioning Scheme: Fixed (Viewport Locked)

**La Maîtrise de CSS : De zéro à expert en 100 leçons** *(Alternative, slightly punchier version using a common French idiomatic structure for full coverage: CSS : Maîtrisez l'essentiel en 100 leçons, but the first option is closer to the original progression.)*

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

  1. Out of Flow: The element's original space is collapsed.
  2. Fixed to Viewport: The element is positioned relative to the browser window itself.
  3. Offsets Apply: top, right, bottom, and left position 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.