Bootstrap 3 using affix to fixing navbar position to top when scrolling

kjaer108 picture kjaer108 · Oct 31, 2013 · Viewed 35.9k times · Source

This is driving me nuts... This might be simple by I'm not hitting the nail: please give a hint :-)

I'm trying to play with Bootstrap 3 for a new layout for my site. I want the navbar to pin to the top of the screen when I scroll.

I got it working but the content below navbar shifts when the affix class kicks in. I can't find my way around it.

Answer

Mo. picture Mo. · Mar 3, 2014

There are two option either javascript or HTML5 data- attribute

Via data attributes To easily add affix behavior to any element, just add data-spy="affix" to the element you want to spy on. Use offsets to define when to toggle the pinning of an element.

<div data-spy="affix" data-offset-top="60" data-offset-bottom="200">
  ...
</div>

Via JavaScript Call the affix plugin via JavaScript:

  $('#my-affix').affix({
    offset: {
      top: 100
    , bottom: function () {
        return (this.bottom = $('.footer').outerHeight(true))
      }
    }
  })

DEMO http://jsfiddle.net/6P5sF/56/

reference http://getbootstrap.com/javascript/#affix-examples