Fixed and Sticky Positioning Explained

Fixed Positioning

position: fixed removes an element from normal flow and pins it relative to the browser viewport itself, not to any ancestor. It stays in the same spot on screen even as the page scrolls.

.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
}

This is the pattern behind sticky headers that never scroll away, or a floating "back to top" button.

Sticky Positioning

position: sticky behaves like relative until the page scrolls to a point where the element would move out of view - at that point it "sticks" in place, as if switching to fixed, but only within the bounds of its parent container.

.section-heading {
  position: sticky;
  top: 0;
}

As the user scrolls past .section-heading, it sticks to the top of the viewport - but only until its parent container scrolls out of view entirely, at which point it scrolls away with the rest of that section.

Fixed vs Sticky at a Glance

PropertyFixedSticky
Reference pointThe viewport, alwaysIts own parent container
Stays visible always?Yes, for the whole pageOnly while its parent is in view
Typical usePersistent header/footer, floating buttonsSection headings, sticky table headers

A Common Gotcha

A sticky element will not stick if any ancestor has overflow: hidden, overflow: auto or overflow: scroll - the scrolling context created by that ancestor takes over, and the sticky behavior stops working as expected.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.