A header that stays visible

Keep a header in view as the page scrolls.

What to build

A sticky header above long content.

Requirements

  • header has position: sticky and top: 0.
  • header has a z-index of 10.
  • header has a background of white, so that text does not show through.
  • body has no overflow setting.

Constraints

Do not use position: fixed.

Example

th { position: sticky; top: 0; } keeps table headers visible.

Why it works

Sticky stays in the flow, so nothing needs to reserve space for it. The background stops the content scrolling underneath from showing through.

Hints

Hint 1

sticky needs a threshold.

Hint 2

A header usually sits above the content that scrolls beneath it.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sticky</title>
  <style>
    main { height: 800px; }
    header {
      position: sticky;
      top: 0;
      z-index: 10;
      background: white;
    }
  </style>
</head>
<body>
  <header>Site title</header>
  <main>Long content</main>
</body>
</html>

Lesson: Positioning and stacking →