Codectionary / Developer documentation / CSS

position Property

The position property controls how an element is positioned in the document. static is the default, following normal flow. relative positions an element relative to its normal position. absolute removes it from flow entirely, positioning it relative to its nearest positioned ancestor. fixed positions relative to the viewport, staying in place during scroll. sticky toggles between relative and fixed based on scroll position.

Syntax

position: static | relative | absolute | fixed | sticky;

Examples

relative and absolute Together

The most common pattern: a relatively-positioned parent containing an absolutely-positioned child.

.card {
  position: relative; /* establishes a positioning context for children */
}

.badge {
  position: absolute;
  top: 10px;
  right: 10px; /* positioned relative to .card, not the page */
}

fixed for a Persistent Header

Keeping an element in place regardless of scrolling.

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

sticky for a Sticky Section Heading

An element that scrolls normally until it hits a threshold, then sticks.

.section-heading {
  position: sticky;
  top: 0; /* sticks once it reaches 0px from the top of the scroll container */
  background: white;
}

Parameters and values

  • static (keyword): Default - normal document flow, top/left/etc have no effect
  • relative (keyword): Offset from its normal position, still occupies original space
  • absolute (keyword): Removed from flow, positioned relative to nearest positioned ancestor
  • fixed (keyword): Positioned relative to the viewport, stays put while scrolling
  • sticky (keyword): Relative until a scroll threshold, then behaves like fixed

Best practices

  • Give an absolutely-positioned element's closest meaningful ancestor position: relative, or it will position relative to the whole page instead
  • Use sticky for section headers, table headers, or sidebars that should follow scrolling within a bound, not for full free-floating overlays
  • Remember absolutely and fixed-positioned elements are removed from normal flow - other elements act as if they are not there
  • Combine position: fixed with a high z-index for overlays and modals to ensure they render above other content

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation