CSS Sticky Header Example

A sticky header remains fixed at the top of the screen when a user scrolls down the page.

This is commonly used for navigation bars so users can easily access menu links while scrolling.

CSS provides the position sticky property to create this behavior without using JavaScript.

HTML Structure

HTML
Sticky Header HTML Example
<header class="header">
  <h2>My Website</h2>
</header>

<nav class="menu">
  <a href="#">Home</a>
  <a href="#">Projects</a>
  <a href="#">Contact</a>
</nav>

<div class="content">
  <p>Scroll the page to see the sticky effect.</p>
</div>

CSS Sticky Header Code

CSS
Sticky Header CSS Example
body{
  margin:0;
  font-family:Arial;
}

.header{
  background:#222;
  color:white;
  padding:20px;
  text-align:center;
}

.menu{
  background:#444;
  padding:10px;
  position:sticky;
  top:0;
  z-index:1000;
}

.menu a{
  color:white;
  margin-right:15px;
  text-decoration:none;
}

How Sticky Position Works

The sticky position keeps the element in its normal position until the page scroll reaches a defined point.

After reaching that point, the element becomes fixed at the top of the page.

CSS
Sticky Property
.menu {
  position: sticky;
  top: 0;
}

Advantages of Sticky Headers

  • Improves website navigation
  • Keeps important links visible
  • Enhances user experience
  • Requires no JavaScript

Conclusion

CSS sticky headers are widely used in modern web design to keep navigation visible while users scroll.

Using the position sticky property makes it simple to create responsive and user-friendly navigation bars.