How to Create a Sticky Navbar with CSS and JavaScript

A sticky navigation bar, also known as a fixed navigation bar, is a useful tool for any website.

It stays visible at the top of the page even when the user scrolls down.

In this tutorial, we will show you how to create a sticky navbar using CSS and JavaScript.


HTML Structure

First, let’s create the basic structure of the navigation bar using HTML.

The navigation bar should be wrapped in a container element, typically a nav or header tag.

Inside the container, you can add your navigation links. Here’s an example:

<header id="navbar">
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

CSS Styles

Next, let’s add some basic styles to the navigation bar using CSS.

We will set the width of the container to 100% of the viewport and add a background color.

#navbar {
  width: 100%;
  background-color: #333;
}

JavaScript Function

To make the navigation bar sticky, we need to add a JavaScript function.

The function should check the position of the navigation bar relative to the top of the page and apply a class to it when it reaches a certain threshold.

window.onscroll = function() {
let navbar = document.getElementById("navbar");
if (window.pageYOffset >= navbar.offsetTop) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
};

Sticky Class

Finally, let’s create the sticky class that we added in the JavaScript function.

This class will give the navigation bar a fixed position at the top of the page and add a box shadow.

.sticky {
position: fixed;
top: 0;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

Complete Example

<header id="navbar">
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

<style>
  #navbar {
    width: 100%;
    background-color: #333;
  }

  .sticky {
    position: fixed;
    top: 0;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  }
</style>

<script>
  window.onscroll = function() {
    let navbar = document.getElementById("navbar");
    if (window.pageYOffset >= navbar.offsetTop) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
};
</script>

Conclusion

Creating a sticky navigation bar is a great way to improve the user experience on your website.

With just a few lines of HTML, CSS, and JavaScript, you can create a functional and stylish navigation bar that stays visible as the user scrolls down the page.

You can try experimenting with different styles and colors to find the perfect design for your website.