samtodd
samtodd

Reputation: 539

Bootstrap affix attribute to have a fixed nav below a header

I'm trying to create a page with a header, and a navigation below that's fixed when you scroll to a certain point.

I'm trying to use the built in 'affix' plugin but I'm struggling a little. I've fixed a couple problems with the navigation not sitting in the same place which was adding these lines..

.navbar.affix {
top:0px;
width:100%;
z-index:11;}

However, when it fixes it to the top, the page jumps up and therefore it's not a smooth transition. I understand why, I think, because the space where the navigation was is now not being used, so the rest of the content shifts up..

What do I need to do so that when the navigation gets fixed, the content doesn't shift up?

Thanks in advance.

Demo - http://samtodd.co.uk/header-navigation.html

Upvotes: 2

Views: 926

Answers (1)

omma2289
omma2289

Reputation: 54629

Here's a javascript solution:

$('.navbar[data-spy="affix"]').on('affix.bs.affix', function () {
    var $this = $(this);
    var $fix = $('<div class="affix-height-fix">').height($this.outerHeight(true));
    $this.after($fix);
}).on('affix-top.bs.affix', function () {
    $(this).next('.affix-height-fix').remove();
});

Basically it adds a new element with the same height as the navbar when it gets fixed at the top of the page so the rest of the elements don't shift up. The added element is removed when the navbar resets its position.

Upvotes: 1

Related Questions