SyntaxStudy
Sign Up
CSS Building a Fixed Header
CSS Intermediate 5 min read

Building a Fixed Header

Fixed Header Pattern

A fixed navigation header stays at the top of the viewport as the user scrolls. Compensate for it by adding top padding equal to the header height.

Example
header.site-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: white;
  border-bottom: 1px solid #eee;
  z-index: 500;
  display: flex;
  align-items: center;
  padding: 0 2rem;
}

/* Offset page content */
main {
  padding-top: 64px; /* Same as header height */
}

/* Dynamic using CSS variable */
:root { --header-height: 64px; }
header { height: var(--header-height); }
main   { padding-top: var(--header-height); }
Pro Tip

Store the header height in a CSS variable — every element that needs to account for it can reference the same variable.