Learn how to create a sticky header using only CSS. Improve site navigation with this simple, modern web development technique—no JavaScript required!
Table of content
Sticky headers are everywhere in modern web design. They help keep your main navigation visible as users scroll down the page, improving usability and keeping your content accessible. In this article, we’ll explore how to create a sticky header using just CSS—no JavaScript necessary. It’s simple, efficient, and works in all modern browsers!
A sticky header is a section (usually the top navigation bar) that stays fixed at the top of the browser window as you scroll. This ensures that navigation options or important messages are always visible.
position: sticky
is supported in all major browsers.position: sticky
The cornerstone of a CSS-only sticky header is the position: sticky
property. Unlike position: fixed
, which always pins the element, sticky
transitions the element from relative to fixed based on your scroll position.
header {
position: sticky;
top: 0;
background: #fff;
z-index: 1000;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
<header>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
</header>
header {
padding: 1rem 2rem;
background: #fff;
border-bottom: 1px solid #eee;
}
nav a {
margin-right: 1.5rem;
text-decoration: none;
color: #222;
}
Now, apply the position: sticky
property to your header. Set top: 0;
to keep it at the top.
header {
position: sticky;
top: 0;
z-index: 1000;
}
<body>
<header>...</header>
<main>
<section>Lots of page content...</section>
<section>...scroll down and header stays!</section>
</main>
</body>
z-index
value is high enough to stay on top of other elements.overflow: hidden
or overflow: auto
. Sticky only works properly if the ancestor’s overflow is visible (the default).With just a few lines of CSS, you can add a sticky header to your website, enhancing navigation and keeping important links accessible for your users. Experiment with styles and transitions to make your sticky header shine!