Shrink Sticky Navbar on Scroll Down – Bootstrap 4

Bootstrap navigation bar height is dependent on the height and padding of the following elements

  • Brand name/logo
  • Line height on any element inside the navbar
  • Padding on the main navbar element
  • Line height and padding on the links

To shrink the navbar in scroll down you will need to manipulate the attributes of these elements through CSS and Jquery (plain vanilla javascript will also work – but i dont have code for that).

Let us get started.

Add a new class/id to the navigation bar.

<navbar class="... ... primary-nav" id="primary-nav">

Add a bit of transition style to make the shrinking smooth

.primary-nav {
    transition: all 0.4s ease-in-out;
    -webkit-transition: all 0.4s ease-in-out;
    -moz-transition: all 0.4s ease-in-out;
 }

Add a new class to your stylesheet that will be applied to the navigation bar on scrolling down.

   .shrink {
        padding-top: 0 !important;
        padding-bottom: 0 !important;
        min-height: 55px !important;
    }

You can set the minimum height to any value you want. This value is the height of shrunk navbar.

If your brand name/logo has some height set on it, you will need to fix that too. I prefer to set the height of this element to 0 but you can set it to any desired value.

    .shrink .navbar-brand {
        height: 0 !important;
        line-height: 0 !important;
    }

Next, remove the padding on the link elements (or set them to desired values)

    .shrink a {
        padding-top: 0 !important;
        padding-bottom: 0 !important;       
    }

Finally add jQuery

     $(document).on("scroll", function(){

            if ($(document).scrollTop() > 80){
                $(".primary-nav").addClass("shrink");
            } else {
                $(".primary-nav").removeClass("shrink");
            }

      });

This Jquery code applies a class shrink to the navbar when scrolling down. Notice the value 80 above, this value determines when shrinking should start. Change it to fit your requirement.

Thats it! Apply the code in your theme and see the shrinking in action!

Did that work for you? Let me know in the comments below.