CSS Sticky Position

Sticky positioning is a hybrid: an element scrolls normally until it reaches a set offset, then locks in place until its container scrolls away.

position: sticky gives you the best of two worlds. The element behaves like a normal relative element while it is on screen, but once you scroll it to a threshold you define, it sticks there like a fixed element. It is perfect for section headings and table headers.

The required offset

Sticky does nothing on its own. You must specify at least one offset, usually top, to tell the browser where the element should stick. Without it, the element just scrolls away like normal.

A sticky toolbar

<!DOCTYPE html>
<html>
<head>
<style>
.toolbar {
  position: sticky;
  top: 0;
  background: #ffffff;
}
</style>
</head>
<body>

<div class="toolbar">
  <button>Save</button>
  <button>Cancel</button>
</div>

</body>
</html>

Stuck within its container

A sticky element can only stick while its parent is on screen. Once you scroll past the bottom of the containing element, the sticky item scrolls off with it. This confines each sticky heading to its own section.

Section headings

<!DOCTYPE html>
<html>
<head>
<style>
.section h2 {
  position: sticky;
  top: 60px;
}
</style>
</head>
<body>

<div class="section">
  <h2>Chapter One</h2>
  <p>Content for this section goes here.</p>
</div>

</body>
</html>
Note: Sticky quietly fails if any ancestor has overflow set to hidden, scroll, or auto. If your sticky element will not stick, check the overflow on its parents first.

Sticky versus fixed

  • fixed is pinned to the viewport from the start and never scrolls.
  • sticky scrolls with the page until it hits its offset, then holds.
  • sticky respects its container's bounds; fixed ignores them.

Exercise: CSS Position

What is the default position value applied to elements that don't specify one?