What is the difference between position relative, absolute, and fixed?

Relative keeps the element in normal flow; absolute removes it from flow and positions relative to its nearest positioned ancestor; fixed sticks to the viewport.

CSSLayout

Overview

CSS positioning controls where and how an element is placed on the page. The `position` property combined with `top`, `right`, `bottom`, and `left` offsets determines the final position.

Key Points

  • •`static` (default): element follows the normal document flow; top/left/etc. have no effect.
  • •`relative`: stays in normal flow, but you can nudge it with top/left without affecting other elements.
  • •`absolute`: removed from normal flow; positioned relative to the nearest ancestor with `position` set to anything other than `static`.
  • •`fixed`: like absolute but positioned relative to the viewport stays in place when scrolling.
  • •`sticky`: hybrid of relative and fixed; sticks at a threshold while scrolling.

Examples

Relative: nudge without removing from flow

css
.nudged {
  position: relative;
  top: 10px;   /* moved down 10px, original space is still occupied */
  left: 20px;
}

Absolute: position inside a container

css
.container {
  position: relative;  /* establishes positioning context */
  width: 300px;
  height: 200px;
}
.badge {
  position: absolute;
  top: 8px;
  right: 8px;  /* 8px from container's top-right corner */
}

If no ancestor has a position set, absolute falls back to the <html> element.

Fixed: sticky header that stays on scroll

css
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 100;
}

Sticky: stick at scroll threshold

css
.section-header {
  position: sticky;
  top: 0;       /* sticks when it reaches the top of the viewport */
  background: white;
}

Pro Tip

A common gotcha: `position: absolute` looks for the nearest ancestor with any position value other than `static`. Always add `position: relative` to the intended containing element even if you don't set any offsets on it.