CodeBlanks Logo Icon CodeBlanks

Position fixed and sticky

CSS course · Beginner · Lesson 70/82

Learn position: fixed and sticky values.

Pin to the window with position: fixed

position: fixed takes an element out of the flow and pins it relative to the browser window (viewport). Even when the page scrolls, the element stays put. top, right, bottom, left place it against the window edges.

This value is mostly used for fixed headers and back-to-top buttons. When the visitor scrolls down, these elements stay visible.

Stick past a threshold with position: sticky

position: sticky is a hybrid value. It first behaves as in normal flow; but once scroll crosses a set threshold, it starts acting like fixed and sticks to the given position.

For example, with top: 0 and position: sticky, the element starts in its normal spot; as the user scrolls down, it sticks to the top edge and stays there. This is ideal for section headings and sidebars.

When to use which?

If a header must always be visible and not scroll away, pick position: fixed. The element leaves the flow; the content below it must add top margin to avoid slipping under the header.

If a section heading should start in its normal spot and only stick during scroll, use position: sticky. The element stays in flow; no extra spacing is needed.

Exercise Pin the header

Write a header.site class selector and assign three declarations: position: fixed, top: 0, left: 0. The header will then be pinned to the top-left corner of the browser window.

Show example solution
/* pin the header */
header.site {
  position: fixed;
  top: 0;
  left: 0;
}

Test yourself

  1. Which scenario fits position: fixed?

    • Paragraph text splits into two columns
    • Header stays put during scroll
    • List markers change shape
    • Link color marks as visited
    Show answer

    Header stays put during scroll — Correct. fixed is ideal for headers and buttons that must stay visible during scroll.

  2. Make the sidebar sticky

    .sidebar {
      ____;
      top: 0;
    }
    Show answer
    .sidebar {
      position: sticky;
      top: 0;
    }
  3. Match each value to its meaning

    fixed
    Pinned to viewport
    sticky
    Sticks past threshold
    absolute
    Relative to container

All lessons in Beginner