What is position?

The position property controls how an element is placed: either in the normal document flow (static, relative, sticky) or taken out of it (absolute, fixed). Combined with the offset properties top, right, bottom, left (or inset), it lets you nudge, overlay, pin or stick elements.

The five values in one sentence each

  • static (default): normal flow; offsets and z-index have no effect.
  • relative: stays in flow, can be nudged with offsets, and becomes the reference point for absolutely positioned children.
  • absolute: removed from flow; positioned relative to the nearest positioned ancestor.
  • fixed: removed from flow; positioned relative to the viewport, stays put while scrolling.
  • sticky: behaves like relative until a scroll threshold (top: 0), then sticks within its parent.

Key concept: the containing block

An absolutely positioned element looks for the nearest ancestor whose position is anything other than static. That is why the classic pattern is a relative parent with an absolute child (badges, close buttons, overlays).

Useful shorthands

  • inset: 0 is the same as top: 0; right: 0; bottom: 0; left: 0 (fills the containing block).
  • Centering: position: absolute; inset: 0; margin: auto; with a width and height, or top: 50%; left: 50%; translate: -50% -50%.

Interview tip

Positioned elements also create stacking contexts with z-index; mention it, because overlay bugs often come from that.

Code example

html
1<style>
2 body { font-family: system-ui; height: 900px; }
3 .card { position: relative; width: 240px; padding: 16px; border: 2px solid #0b1020; margin-top: 40px; }
4 .badge { position: absolute; top: -10px; right: -10px; background: #e11d48; color: white; border-radius: 999px; padding: 2px 8px; }
5 .nudge { position: relative; left: 20px; color: #2b4bff; }
6 .fab { position: fixed; right: 16px; bottom: 16px; background: #ffd84d; border: 2px solid #0b1020; padding: 10px 14px; border-radius: 999px; }
7 .sticky { position: sticky; top: 0; background: #0b1020; color: white; padding: 8px; }
8</style>
9<div class="sticky">I stick to the top while you scroll</div>
10<div class="card">
11 Card with a badge
12 <span class="badge">3</span>
13 <p class="nudge">relative: nudged 20px but my space stays</p>
14</div>
15<button class="fab">fixed</button>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app