CSS Tutorial · CSS Layout · Lesson 11 of 19

CSS Position

static, relative, absolute, fixed and sticky positioning, and z-index.

Position values

Value Positioned relative to
static normal flow (default)
relative its normal position; also becomes the anchor for absolute children
absolute the nearest positioned ancestor; removed from the flow
fixed the viewport — stays put when scrolling
sticky normal flow until a scroll threshold, then sticks

top, right, bottom and left move positioned elements; z-index controls stacking order.

Example 1Try it yourself
<style>
  .card { position: relative; width: 240px; height: 120px; background: #e0e7ff; border-radius: 10px; font: 14px system-ui; padding: 12px; }
  .badge { position: absolute; top: -8px; right: -8px; background: #dc2626; color: white; border-radius: 999px; padding: 2px 9px; font-size: 12px; }
  .nudge { position: relative; left: 20px; color: #4338ca; }
</style>
<div class="card">
  Card content
  <span class="badge">3</span>
  <p class="nudge">Moved 20px right (relative)</p>
</div>

Scroll inside the box below to see position: sticky:

Example 2Try it yourself
<style>
  .scroller { height: 160px; overflow: auto; border: 1px solid #cbd5e1; font: 14px system-ui; }
  .scroller h4 { position: sticky; top: 0; margin: 0; padding: 6px; background: #0f172a; color: white; }
  .scroller p { margin: 8px; }
</style>
<div class="scroller">
  <h4>Sticky header A</h4><p>Item</p><p>Item</p><p>Item</p><p>Item</p>
  <h4>Sticky header B</h4><p>Item</p><p>Item</p><p>Item</p><p>Item</p>
</div>

Test yourself

An absolutely positioned element is placed relative to what?

  1. The page body always
  2. Its nearest positioned ancestor
  3. Its previous sibling
  4. The viewport always
Show answer

Answer: Its nearest positioned ancestor