Lesson 21 +10 XP

Position: static, relative, absolute, fixed, sticky

The position Property

position moves elements around by offsetting them from a spot.

static (default)

Normal flow. Offsets (top, left, etc.) do NOTHING:

div {
  position: static;
}

relative

Moves an element relative to its normal spot (keeps its original space):

div {
  position: relative;
  top: 20px;
  left: 30px;
}
  • top/right/bottom/left offsets.
  • original space is preserved.

absolute

Removes the element from flow and positions it relative to the nearest positioned ancestor (or the page):

.modal {
  position: absolute;
  top: 0;
  right: 0;
}

IDEA: give the parent position: relative and child absolute to anchor overlays!

fixed

Anchored to the browser window. Scrolls away? NO, it stays on screen:

.nav {
  position: fixed;
  top: 0;
  width: 100%;
}

Great for header bars and "back to top" buttons.

sticky

Trades: behaves like relative until it hits a scroll threshold, then sticks like fixed:

.sidebar {
  position: sticky;
  top: 10px;
}

TL;DR

  • static: normal flow (default).
  • relative: offset from its own spot, keeps space.
  • absolute: breaks out, positions against nearest positioned parent.
  • fixed: stays glued to viewport while scrolling.
  • sticky: sticks after you scroll past a point.