Search code examples
jquerycsstwitter-bootstrapaffix

Bootstrap Affix fixed header after 100px making content jump


I'm using Bootstrap Affix on my header and I want it to become fixed once the page is scrolled 100px. I have added in the jquery like so:

$('#navbar').affix({
      offset: {
        top: 100,
      }
    });

The problem is when I scroll the content on the page jumps up. I've added a wrapper with a min height but this doesn't solve the problem.

Can anyone help please?

Link to fiddle: https://jsfiddle.net/b5fusmsn/12/


Solution

  • The flicker/jump is because the navbar is changing from position:static to postition:fixed. When the affix is applied at 100px, which is close the height of the navbar 92px, it's always going to "jump" unless you had a div of 100px in height above the navbar like in this question.

    In your case, it looks like you're just trying to shrink the navbar padding after scrolling 100px, so in that case always keep the navbar postion:fixed and just adjust the padding when .affix is applied...

    https://jsfiddle.net/etxyk0y1/1/

    .navbar {
        min-height: 50px;
        z-index: 99998;
        background:red;
        width:100%;
        position: fixed;
        transition: all .5s;
        top: 0;
    }
    
    .affix-top.navbar {
        padding-bottom: 20px;
        border: 1px solid transparent;
        padding-top: 20px;
    }
    
    .affix.navbar {
        padding-top: 10px;
        padding-bottom: 10px;
        font-size: 0.9em;
        border-bottom: 1px solid #f9f7f3;
        transition: all .5s;
    }
    

    Use the nav-wrapper to keep spacing between the fixed navbar and the content.

    .nav-wrapper {
        padding-top: 100px;
    }