Fix bootstrap anchor tags position using fixed nav bars

     
9th May, 2013 by

If you’re using a .navbar-fixed-top fixed to top navbar in Twitter Bootstrap you probably have noticed your anchor ahref links no longer line up correctly.

The easiset way to fix this is to the use the <section id="MyAnchor"> tag with a padding-top equal to the padding you’ve added to the body.

So for example if you have:

.body {
padding-top:40px
}

You will then want to add the same padding to your section CSS:

section {
padding-top:40px;
}

If the 40px gap above each section is going to mess with your design mojo you can add a negative margin-bottom. So for example:

section {
padding-top:40px;
margin-top:-40px;
}

you can then use the following HTML to link to your on page anchor, which should now align correctly:

<a href="#Mule">Link to Mule</a>
<a href="#Donkey">Link to Donkey</a>
<a href="#Horse">Link to Horse</a>
 
<section id="Mule">
<h1>This is Mule</h1>
<p>A mule is the offspring of a female horse, and a male donkey</p>
</section>
 
<section id="Donkey">
<h1>This is Donkey</h1>
<p>Is a Mule Daddy</p>
</section>
 
<section id="Horse">
<h1>This is Horse</h1>
<p>Is a Mule Mummy</p>
</section>
  • Just wanted to let you know this is awesome and works perfectly. Thank you!

  • Should that read “margin-top” in the red text?

  • Valentin Darricau

    Awesome!

  • Federico Laport Rivas

    Used it today. Again.