Retour au cours

Lesson 48: Positioning Scheme: Sticky (The Best of Both Worlds)

**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.)*

48. Positioning Scheme: Sticky (The Best of Both Worlds)

position: sticky is a hybrid position scheme. An element is treated as relative until it hits a specified offset threshold, at which point it becomes fixed relative to the viewport.

How Sticky Positioning Works

  1. The element is in the normal flow (relative).
  2. You must define a threshold using one of the offset properties (top, right, bottom, or left).
  3. When the container scrolls and the element's edge touches that defined threshold, the element locks (fixed) until its parent container scrolls completely out of view.

css .sticky-header { position: sticky; top: 0; /* Becomes fixed when the top of the element hits the top of the viewport / background-color: white; padding: 10px; border-bottom: 1px solid #ccc; z-index: 10; / Important for ensuring it overlays other elements */ }

Requirements for Sticky to Work

  • The parent container must be large enough to allow the sticky element to scroll for a while.
  • A top, right, bottom, or left offset value must be specified.
  • The parent element must not have overflow: hidden, scroll, or auto set, as this restricts the scrolling context.