Boxes and positioning

Positioning

Use relative, absolute, fixed, and sticky positioning while understanding containing blocks and removal from normal flow.

9 minute lesson

~~~

position changes how offsets such as top and inset-inline-end work.

  • relative keeps the original space and offsets the box visually.
  • absolute removes the box from normal flow and positions it against a containing block.
  • fixed normally positions against the viewport.
  • sticky behaves normally until it reaches an offset, then sticks within its scroll container.

For an absolute badge inside a card:

.card { position: relative; }
.badge {
  position: absolute;
  inset-block-start: 0.5rem;
  inset-inline-end: 0.5rem;
}

The card becomes the badge’s containing block because it is the nearest positioned ancestor. Without it, the badge may position against a more distant ancestor or the initial containing block.

Sticky positioning requires a non-auto inset on the axis that should stick. It follows the nearest ancestor with a scrolling mechanism, including one created by overflow: hidden, auto, or scroll. An unexpected overflow ancestor is a common reason a sticky header appears not to work.

Transforms and some containment properties can also establish containing blocks, including for elements that would otherwise be fixed to the viewport.

Use positioning for overlays and anchored details, not as a substitute for page layout. Absolute and fixed content can cover text when users zoom or content grows.

In DevTools, inspect the containing block and scroll containers. Remove ancestors’ position, transform, and overflow one at a time until you can explain the reference box.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →