How do I set the offset for ScrollSpy in Bootstrap?

Bootstrap uses offset to resolve spying only, not scrolling. This means that scrolling to the proper place is up to you.

Try this, it works for me: add an event handler for the navigation clicks.

var offset = 80;

$('.navbar li a').click(function(event) {
    event.preventDefault();
    $($(this).attr('href'))[0].scrollIntoView();
    scrollBy(0, -offset);
});

I found it here: https://github.com/twitter/bootstrap/issues/3316


The trick, as Tim alluded to, is to take advantage of padding. So the problem is, your browser always wants to scroll your anchor to the exact top of the window. if you set your anchor where your text actually begins, it will be occluded by your menu bar. Instead, what you do is set your anchor to the container <section> or <div> tag's id, which the nav/navbar will automatically use. Then you have to set your padding-top for the container to the amount offset you want, and the margin-top for the container to the opposite of the padding-top. Now your container's block and the anchor begin at the exact top of the page, but the content inside doesn't begin until below the menu bar.

If you're using regular anchors, you can accomplish the same thing by using negative margin-top in your container as above, but no padding. Then you put a regular <a target="..."> anchor as the first child of the container. Then you style the second child element with an opposite but equal margin-top, but using the selector .container:first-child +.

This all presumes that your <body> tag already has its margin set to begin below your header, which is the norm (otherwise the page would render with occluded text right off the bat).

Here's an example of this in action. Anything on your page with an id can be linked to by tacking #the-elements-id onto the end of your URL. If you make all of your h tags ad dt tags with ids link-able (Like github does) with some sort of script that injects a little link to the left of them; adding the following to your CSS will take care of the nav-bar offset for you:

body {
    margin-top: 40px;/* make room for the nav bar */
}

/* make room for the nav bar */
h1[id],
h2[id],
h3[id],
h4[id],
h5[id],
h6[id],
dt[id]{
    padding-top: 60px;
    margin-top: -40px;
}