Sticky Navbar on Scroll with HTML CSS JS

Aug 05 20238 minutes
Video Tutorial

You must have seen a secondary Navbar on websites that stick to the top when you scroll. These Navabars are getting popular nowadays if you also want to implement it on your own website then it is straightforward.

You can do this with the help of just fixed or sticky positions in CSS.

So let’s see how you can do this.

#Demo

We are going to style our page such that when we scroll our page looks like this.

image from tutorend.com

#Creating new Project

In this tutorial, I am going to use HTML CSS, and JS all in one single file index.html to make it easier for you to follow instead of navigating through different files.

This is how our basic HTML page looks with the required tags and content.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sticky navbar</title>
    
  </head>
  <body>
    <header id="header">
      <h1>Welcome to Tutorend</h1>
    </header>
    <nav id="navbar" class="">
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Pricing</a></li>
      </ul>
    </nav>

    <div class="content">
      <h2>Content</h2>
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Asperiores ut
        sequi in officia, deleniti nesciunt odio neque eius qui dignissimos enim
        laudantium ducimus quidem aperiam velit dolorum ad esse nulla delectus
        magnam veritatis alias quibusdam aliquid explicabo! Repellendus
        recusandae necessitatibus maiores ullam placeat quisquam, animi commodi
        
        
        Temporibus sequi dolorem iste modi laborum vitae minima commodi
        exercitationem placeat veritatis rem provident facere maxime eligendi
        iusto reiciendis blanditiis quidem harum aspernatur, esse distinctio
        repellendus totam cumque! Dicta officiis eveniet deleniti nulla minus
        dolorum voluptas soluta, ducimus omnis fugiat voluptatum tempora ipsam!
        Maiores dignissimos labore id autem quis eaque laudantium blanditiis
        quisquam! Beatae dolor eum ducimus illum ad ratione, hic harum quia
        repellat! Modi dicta aperiam illum inventore sunt, eius minus vel.
        Laudantium animi, corporis harum ipsa modi aspernatur eaque.
        Necessitatibus, optio! Cumque reiciendis, iusto voluptate dignissimos
        maiores explicabo voluptatem ab laboriosam veritatis!
      </p>

    
    </div>
  </body>
</html>

On this page, you can see there is a header tag to create a top header that will display Welcome to Tutorend , nav will contain our nav links and the rest is going to hold our page content.

Also, we are giving IDs to our header and navbar to later style it by selecting with id.

#Adding styling

Now we can style our Navbar and header with CSS I am writing CSS inside the style tag in index.html itself you may style it from a separate CSS file also.

<style>
      * {
        margin: 0;
        padding: 0;
      }
      #header {
        background-color: #333;
        color: #fff;
        padding: 10px;
      }

      #navbar{
        background-color: #f1f1f1;
        padding: 10px;
        font-size: x-large;       

      }
     
      #navbar ul{
        display: flex;
        gap: 10px;
        list-style: none;
      }

    </style>

#Method 1 : position: sticky

Now we can add position: sticky to the navbar to make it stick when we scroll

   #navbar{
        background-color: #f1f1f1;
        padding: 10px;
        font-size: x-large;

        position: sticky;
        top: 0;
        z-index: 100;        

      }

also set the top to 0 to make it stick on the top and you may give the z-index so that no other elements overlap the navbar.

Now you will have it, your navbar is sticky on scroll.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sticky navbar</title>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #header {
        background-color: #333;
        color: #fff;
        padding: 10px;
      }

      #navbar{
        background-color: #f1f1f1;
        padding: 10px;
        font-size: x-large;

        position: sticky;
        top: 0;
        z-index: 100;        

      }
     
      #navbar ul{
        display: flex;
        gap: 10px;
        list-style: none;
      }

    </style>
  </head>
  <body>
    <header id="header">
      <h1>Welcome to Tutorend</h1>
    </header>
    <nav id="navbar" class="">
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Pricing</a></li>
      </ul>
    </nav>

    <div class="content">
      <h2>Content</h2>
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Asperiores ut
        sequi in officia, deleniti nesciunt odio neque eius qui dignissimos enim
        laudantium ducimus quidem aperiam velit dolorum ad esse nulla delectus
        magnam veritatis alias quibusdam aliquid explicabo! Repellendus
        recusandae necessitatibus maiores ullam placeat quisquam, animi commodi

        exercitationem placeat veritatis rem provident facere maxime eligendi
        iusto reiciendis blanditiis quidem harum aspernatur, esse distinctio
        repellendus totam cumque! Dicta officiis eveniet deleniti nulla minus
        dolorum voluptas soluta, ducimus omnis fugiat voluptatum tempora ipsam!
        Maiores dignissimos labore id autem quis eaque laudantium blanditiis
        quisquam! Beatae dolor eum ducimus illum ad ratione, hic harum quia
        repellat! Modi dicta aperiam illum inventore sunt, eius minus vel.
        Laudantium animi, corporis harum ipsa modi aspernatur eaque.
        Necessitatibus, optio! Cumque reiciendis, iusto voluptate dignissimos
        maiores explicabo voluptatem ab laboriosam veritatis!
      </p>

      <script>
        const header = document.getElementById("header")
        const navbar = document.getElementById("navbar")

        const height = header.clientHeight;

        window.addEventListener("scroll", ()=>{
            if(window.pageYOffset>= height){
                navbar.classList.add("sticky")
            }else{
                navbar.classList.remove("sticky")
            }
        })


      </script>
    </div>
  </body>
</html>

#Method 2 : position: fixed

Alternatively, we can create a class called .sticky and add it to the navbar dynamically when we scroll based on the scroll position of the page.

This is the sticky class which has a fixed position. full width and z-index=100 so that no other element overlaps it.

   .sticky{
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 100;
      }

And using javascript we can dynamically add this class to navbar.

     <script>
        const header = document.getElementById("header")
        const navbar = document.getElementById("navbar")

        const height = header.clientHeight;

        window.addEventListener("scroll", ()=>{
            if(window.pageYOffset>= height){
                navbar.classList.add("sticky")
            }else{
                navbar.classList.remove("sticky")
            }
        })
     </script>

In this script, we are getting the height of the header and checking if the pageYoffset or top of the page is scrolled up by that height, if it is then we are going to add a sticky class to the navbar otherwise will remove it.

Suppose if the height of header is 50px then we scroll our page 50 px then the navbar will be sticky and when the scroll is reversed or pageYoffset is ls less than 50 px then the sticky class will be removed.

Full code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sticky navbar</title>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #header {
        background-color: #333;
        color: #fff;
        padding: 10px;
      }

      #navbar{
        background-color: #f1f1f1;
        padding: 10px;
        font-size: x-large;  

      }
      .sticky{
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 100;
      }
     
      #navbar ul{
        display: flex;
        gap: 10px;
        list-style: none;
      }

    </style>
  </head>
  <body>
    <header id="header">
      <h1>Welcome to Tutorend</h1>
    </header>
    <nav id="navbar" class="">
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Pricing</a></li>
      </ul>
    </nav>

    <div class="content">
      <h2>Content</h2>
      <p>
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Asperiores ut
        sequi in officia, deleniti nesciunt odio neque eius qui dignissimos enim
        laudantium ducimus quidem aperiam velit dolorum ad esse nulla delectus
        magnam veritatis alias quibusdam aliquid explicabo! Repellendus
        recusandae necessitatibus maiores ullam placeat quisquam, animi commodi
        
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Temporibus vel nam atque dolore maxime accusantium quas dicta doloribus. Quo velit iusto perferendis soluta. Doloremque, dignissimos a. Vitae in hic architecto fugit illum soluta? Dolores quod accusamus corporis explicabo ab quidem ducimus sed. Voluptas architecto modi magni, magnam quia delectus sequi quam ducimus eaque iure aliquid officia maiores soluta voluptates totam nemo perferendis quas labore, natus recusandae! Libero exercitationem laborum, sunt veniam, quis laboriosam, maxime consequatur minus ex distinctio perferendis cum? Odit ratione aspernatur illo quisquam nemo adipisci molestiae voluptate ad, maxime, ab ut mollitia repellendus vitae deleniti, quo et impedit natus id laudantium quasi repudiandae sapiente. Voluptatem a sapiente eligendi doloremque? Quidem pariatur error deleniti esse alias est eius vel? Unde eaque quasi quam aspernatur deserunt esse incidunt iste quidem nemo explicabo veritatis vero voluptas, atque vel necessitatibus doloribus itaque. Sed, vitae nesciunt a tempore, iure provident est nulla, doloribus quod commodi necessitatibus minima ex. Earum quos officia possimus ad minima est delectus itaque laudantium sed, doloremque suscipit totam facilis! Aspernatur ad maiores laboriosam reiciendis impedit quae enim ea earum nam, neque, debitis perspiciatis quod vitae necessitatibus placeat doloremque incidunt facere omnis aperiam saepe ratione! Qui provident accusamus in iste.
        velit explicabo? Pariatur reprehenderit modi nobis quae quia voluptatem
        neque fuga. Magnam veritatis dolore aliquam ea id optio enim,
        consequatur sed voluptate voluptatem aspernatur, vero, omnis accusantium
        itaque nulla earum vel modi eveniet necessitatibus sequi iusto pariatur!
        Nobis omnis porro obcaecati, nulla eligendi vitae neque similique iure
        blanditiis accusantium quasi nihil architecto repellendus, perspiciatis
        debitis ad numquam. Illum amet numquam beatae! Architecto nesciunt
        pariatur reiciendis reprehenderit tempora illum, necessitatibus ipsum
        rem dicta ipsam labore blanditiis quo autem sed recusandae fuga quos?
        Explicabo omnis eius consequatur perspiciatis. Obcaecati neque maxime
        aliquid eum quibusdam nobis, alias iure. Corporis, repudiandae. Iusto at
        omnis quisquam, temporibus autem adipisci? Minus minima voluptatem,
        incidunt nulla deserunt dicta debitis in natus aut doloribus consectetur
        suscipit quis id unde, ipsa tenetur, quos ut molestias! Sapiente facilis
        deleniti corporis dignissimos nemo, assumenda officiis illum, mollitia,
        exercitationem corrupti illo quis deserunt! Laudantium cupiditate vero
        repellat expedita voluptates, iste, autem ullam doloremque consequuntur
        voluptatibus optio, aperiam rerum maxime! Error, impedit quaerat!
        Temporibus sequi dolorem iste modi laborum vitae minima commodi
        exercitationem placeat veritatis rem provident facere maxime eligendi
        iusto reiciendis blanditiis quidem harum aspernatur, esse distinctio
        repellendus totam cumque! Dicta officiis eveniet deleniti nulla minus
        dolorum voluptas soluta, ducimus omnis fugiat voluptatum tempora ipsam!
        Maiores dignissimos labore id autem quis eaque laudantium blanditiis
        quisquam! Beatae dolor eum ducimus illum ad ratione, hic harum quia
        repellat! Modi dicta aperiam illum inventore sunt, eius minus vel.
        Laudantium animi, corporis harum ipsa modi aspernatur eaque.
        Necessitatibus, optio! Cumque reiciendis, iusto voluptate dignissimos
        maiores explicabo voluptatem ab laboriosam veritatis!
      </p>

      <script>
        const header = document.getElementById("header")
        const navbar = document.getElementById("navbar")

        const height = header.clientHeight;

        window.addEventListener("scroll", ()=>{
            if(window.pageYOffset>= height){
                navbar.classList.add("sticky")
            }else{
                navbar.classList.remove("sticky")
            }
        })


      </script>
    </div>
  </body>
</html>

#Conclusion

I hope you were able to achieve a sticky navbar with either position: sticky or fixed.

Thanks for reading this tutorial and hope you will find other tutorials helpful too, Happy Coding :).