CSS ยท Chapter 18 of 44

CSS Position

The position property controls how an element is placed: static (default flow), relative (offset from its normal position), absolute (positioned relative to nearest positioned ancestor), fixed (relative to the viewport), and sticky (a hybrid).

Top, right, bottom, and left properties work together with position to place elements precisely.

Syntax
position: relative | absolute | fixed | sticky;
top: 0; left: 0;

Static and relative

static is the default; offsets don't apply. relative shifts an element from its normal position without affecting other elements' layout.

Absolute, fixed, and sticky

absolute positions relative to the nearest ancestor with position set (not static). fixed stays in place during scrolling. sticky switches between relative and fixed based on scroll position.

Example 1 (css)
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Output
A modal box fixed in the center of the viewport, even when scrolling

position: fixed keeps the modal in place, and the transform centers it precisely.

Key points

  • static is the default with no offset behavior.
  • relative offsets from the element's normal position.
  • absolute positions relative to the nearest positioned ancestor.
  • fixed stays anchored to the viewport during scroll; sticky toggles between relative and fixed.
๐Ÿ’ก Note: An absolutely positioned element needs a positioned ancestor (relative/absolute/fixed) to position against, or it uses the whole page.

๐Ÿ“ Quick Quiz

1. Which position value is the default?

2. Which value keeps an element fixed to the viewport while scrolling?

3. Absolute positioning is relative to: