Back to course

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

CSS Mastery: From Zero to Hero in 100 Lessons

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.