Course contentsShow
← Web Development
Lesson 222 of 2,9824. CSS Layout FoundationsFree lesson

Sticky Positioning Fundamentals

How sticky positioning toggles between relative and fixed based on scroll position.

What You'll Learn

You'll learn how sticky positioning creates elements that act as relatively positioned until they reach a scroll threshold, then "stick" in place like fixed elements.

The Hybrid Behavior of Sticky

Sticky positioning is like a toggle switch triggered by scrolling. An element with position: sticky starts out behaving exactly like position: relative — it sits in the normal document flow. But when you scroll the page and that element reaches a specific point (defined by top, right, bottom, or left), it suddenly switches to acting like position: fixed, sticking to that spot on the screen.

Think of it like a Post-it note on a document you're scrolling through. At first, the note moves with the document (relative behavior). But once it reaches the top of your screen, it sticks there (fixed behavior) until you scroll back up, and then it returns to its original position in the flow.

How It Works

.sticky-header {
  position: sticky;
  top: 0;
}

This element will:

  1. Start as relative: Flow normally with other content
  2. Become fixed: When its top edge would scroll past the viewport's top (0px from the top)
  3. Stay stuck: As you continue scrolling down
  4. Release: When you scroll back up past its original position

The offset property (top: 0 in this example) tells the browser where to stick the element. Without an offset value, sticky positioning won't work — the browser needs to know the threshold.

Key Takeaway: Sticky positioning combines relative and fixed behaviors, switching automatically based on scroll position within its containing block, creating headers, sidebars, or elements that stick while scrolling.