Junior (0-2 years)HTML & CSS

What is the difference between relative, absolute, fixed and sticky positioning in CSS?

Quick answer

Relative offsets an element from its normal place; absolute positions it against the nearest positioned ancestor; fixed is against the viewport; sticky sits in normal flow until a scroll threshold, then sticks.

position: relative with top/left moves the element but the original space is kept. position: absolute takes it out of flow; the containing block is the nearest ancestor with position other than static (or the initial containing block). That is why a modal overlay needs position: relative on its parent.

fixed stays put when the page scrolls, which is how sticky headers used to be built. sticky is a hybrid: the element scrolls with its container until top: 0 (or similar) is reached, then it behaves like fixed within that container. sticky fails if any ancestor has overflow: hidden.

Key points

  • absolute is relative to the nearest positioned ancestor
  • fixed is relative to the viewport
  • sticky needs a threshold (top/left) and no overflow-hidden ancestors