Skip to main content

Ralsina.Me — Roberto Alsina's website

My Solution For Bootstrap's Freaking Fixed Navigation Bar Hiding Things

This is a well known prob­lem with boot­strap:

If you use a fixed nav­i­ga­tion bar at the top, when­ev­er you fol­low a link to some­where in­side the page, the ac­tu­al link tar­get is go­ing to be hid­den be­low that freak­ing nav­i­ga­tion bar.

There are a ton of so­lu­tion­s, which have two tons of mi­nor is­sues. There seems to be no way to solve this us­ing CSS and JS with­out caus­ing oth­er prob­lem­s.

There are a bunch of JS so­lu­tions around. Here's mine:

<script type="text/javascript">
 $(window).on('hashchange', function(){
     if (location.hash) {
         $('body').animate({scrollTop: $(location.hash).offset().top - $('#navbar').outerHeight(true)*1.2 }, 1);
     }
 });
 $(document).ready(function(){$(window).trigger('hashchange')});
 </script>

It works well, is short and has de­cent brows­er cov­er­age. It on­ly fails in the cor­ner case of click­ing on the same in­ter­nal link twice (which, who cares).