How to create: slide down the navigation bar during scrolling

Learn how to use CSS and JavaScript to slide the navigation bar down during scrolling.

Try It Yourself

How to slide down the navigation bar

Step 1 - Add HTML:

Create navigation bar:

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

Step 2 - Add CSS:

Set navigation bar style:

#navbar {
  background-color: #333; /* Black background color */
  position: fixed; /* Make it stick/fixed */
  top: -50px; /* Hide the navigation bar 50px outside the top view */
  width: 100%; /* Full width */
  transition: top 0.3s; /* Transition effect when sliding down (up) */
}
/* Set the style for navigation bar links */
#navbar a {
  float: left;
  display: block;
  color: white;
  text-align: center;
  padding: 15px;
  text-decoration: none;
}
#navbar a:hover {
  background-color: #ddd;
  color: black;
}

Step 3 - Add JavaScript:

// When the user scrolls down 20px from the top of the document, slide the navigation bar downwards
// When the user scrolls to the top of the page, slide the navigation bar upwards (50px from the top view)
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("navbar").style.top = "0";
  }
    document.getElementById("navbar").style.top = "-50px";
  }
}

Try It Yourself