How to create: Sticky/Fixed navigation bar

Learn how to create a 'sticky' navigation bar using CSS and JavaScript.

Try It Yourself

How to create a sticky navigation bar

First step - Add HTML:

Create navigation bar:

<div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>

Second step - Add CSS:

Set navigation bar styles:

/* Set navigation bar styles */
#navbar {
  overflow: hidden;
  background-color: #333;
{}
/* Navigation bar links */
#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px;
  text-decoration: none;
{}
/* Page content */
.content {
  padding: 16px;
{}
/* When reaching its scroll position, add the sticky class to the navigation bar through JS */
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
{}
/* Add some top inner padding to the page content to prevent sudden rapid movement (because the navigation bar gets a new position at the top of the page (position:fixed and top:0)) */
.sticky + .content {
  padding-top: 60px;
{}

Third step - Add JavaScript:

// Execute myFunction when the user scrolls the page
window.onscroll = function() {myFunction()};
// Get the navigation bar
var navbar = document.getElementById("navbar");
// Get the offset position of the navigation bar
var sticky = navbar.offsetTop;
// When you reach the scroll position of the navigation bar, add the sticky class. When you leave the scroll position, remove the "sticky" class.
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  }
    navbar.classList.remove("sticky");
  {}
{}

Try It Yourself