Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a sticky header

Short answer

Give the header position: sticky and top: 0. Scroll the box below:

<style>
  .page { height: 160px; overflow: auto; border: 1px solid silver; }
  .page header { position: sticky; top: 0; padding: 8px 12px; background: navy; color: white; }
  .page p { margin: 12px; }
</style>
 
<div class="page">
  <header>My Site</header>
  <p>Line 1</p><p>Line 2</p><p>Line 3</p><p>Line 4</p><p>Line 5</p><p>Line 6</p>
</div>

On a real page the whole window scrolls, so the box with overflow: auto is not needed — the two properties on header are enough.

How it works

A sticky element behaves like a normal one until it reaches the edge set by top. Then it "sticks" and stays there while its parent is visible. The header needs an opaque background, or the text will show through it, and z-index lifts it above positioned cards and images.

How fixed differs

position: fixed also keeps the header in place, but takes it out of the flow: the content slides under it, and you have to add a top offset. Sticky keeps its place in the flow.

Common mistake

Sticky silently fails when one of the ancestors has overflow: hidden or overflow: auto: the element sticks to that ancestor, not to the window. Another cause is a missing top: without it there is nothing to stick to.

Functions used in this recipe

  • position — How an element is positioned: in the normal flow or by offsets.
  • top, right, bottom, left — The offsets of a positioned element from the edges of its reference box: top, right, bottom and left.
  • z-index — Which positioned element is drawn on top when they overlap.

Thanks for reading!

Donate to the site — we work hard for you.