MediumConcept

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

Technology:
CSS
Experience:
Junior,
Mid-level
Topics:
CSS Layout

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.

Detailed explanation

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
  • CSSEasy

    What is the CSS box model?

    Every element is a box made of content, padding, border and margin. The default content-box size counts only the content; border-box includes padding and border in the width you set.

    Intern 路 Junior 路 CSS Layout
  • CSSEasy

    What is the difference between inline, block and inline-block in CSS?

    Block elements start on a new line and take the full available width; inline elements sit in the text flow and ignore width and height; inline-block sits in the flow but accepts width, height, padding and margin on all sides.

    Intern 路 Junior 路 CSS Layout
  • CSSMedium

    What is the difference between Flexbox and CSS Grid?

    Flexbox is one-dimensional (a row or a column). CSS Grid is two-dimensional (rows and columns at once). Use Flexbox for alignment along a line; use Grid when the layout is a real 2D structure.

    Junior 路 Mid-level 路 CSS Layout
  • CSSMedium

    How does CSS specificity work?

    Specificity is the score the browser uses to decide which rule wins: inline styles beat IDs, IDs beat classes/attributes/pseudo-classes, and those beat elements. When scores tie, the last rule in the source wins.

    Junior 路 Mid-level 路 CSS Layout