How to create: shrink navigation menu on scroll

Learn how to adjust the size of the navigation bar using CSS and JavaScript on scroll.

Selbst ausprobieren

How to shrink navigation bar on scroll

First step - Add HTML:

Create navigation bar:

<div id="navbar">
  <a href="#default" id="logo">CompanyLogo</a>
  <div id="navbar-right">
    <a class="active" href="#home">Home</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </div>
</div>

Second step - Add CSS:

Set navigation bar style:

/* Create a sticky/fixed navigation bar */
#navbar {
  overflow: hidden;
  background-color: #f1f1f1;
  padding: 90px 10px; /* Larger padding, which shrinks on scrolling (using JS) */
  transition: 0.4s; /* Add transition effect when padding is reduced */
  position: fixed; /* Sticky/fixed navigation bar */
  width: 100%;
  top: 0; /* At the top */
  z-index: 99;
}
/* Set the style of navigation bar links */
#navbar a {
  float: left;
  color: black;
  text-align: center;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
}
/* Set the style of the logo */
#navbar #logo {
  font-size: 35px;
  font-weight: bold;
  transition: 0.4s;
}
/* Stile für Links bei Mausüberfahren setzen */
#navbar a:hover {
  background-color: #ddd;
  color: black;
}
/* Stile für aktive/aktuelle Links setzen */
#navbar a.active {
  background-color: dodgerblue;
  color: white;
}
/* Einige Links werden auf der rechten Seite angezeigt */
#navbar-right {
  float: right;
}
/* Fügen Sie Responsivität hinzu - Auf Bildschirmen mit einer Breite von weniger als 580 Pixeln wird die Navigationsleiste vertikal anstatt horizontal angezeigt */
@media screen and (max-width: 580px) {
  #navbar {
    padding: 20px 10px !important; /* !important wird verwendet, um sicherzustellen, dass JavaScript den Innenabstand auf kleinen Bildschirmen nicht überdeckt */
  }
  #navbar a {
    float: none;
    display: block;
    text-align: left;
  }
  #navbar-right {
    float: none;
  }
}

Dritter Schritt - Fügen Sie JavaScript hinzu:

// Wenn der Benutzer 80 Pixel von der oberen Seite des Dokuments nach unten scrollt, wird der Innenabstand der Navigationsleiste und die Schriftgröße des Logos angepasst
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.getElementById("navbar").style.padding = "30px 10px";
    document.getElementById("logo").style.fontSize = "25px";
  } else {
    document.getElementById("navbar").style.padding = "80px 10px";
    document.getElementById("logo").style.fontSize = "35px";
  }
}

Selbst ausprobieren