Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML

Local Anchor links with "padding"

Hey!

when using local links ie <a href="#jonathan">Jonathan</a> to link to, for example <h2 id="jonathan"> I wonder if there is some way to add "padding" to the jump. As the navigation for the site im currently doing overflows the h2 when linked directly to it. So I would like the local link to jump me to a bit above my h2.

Solution?

2 Answers

Michael Smart
Michael Smart
16,633 Points

Hi Jonanthan,

I had a similar problem with a site I was working on with a fixed nav. The way I got arround it was to create a <div> in the element above the target element, set the position: absolute; and bottom: (the ammount of padding you want on top of the target element). You would need to set the class/ID of the new <div> to the href of your anchor.

I opted for positioning my new <div> absolute relative to the previous section of my site, however you could position is absolutly relative to the body and set the top: & bottom: in pixels to where you would like your exact target.

<style>
           .div1 {
                      position: relative;                      
           }

           #div2_anchor {
                     position: absolute;
                     bottom: 20px; /* adjust to ammount of padding required */                   
           }   

</style>

<a href="#div2_anchor">Click Me</a>
<div class="div1">
           <h1>This is the previous div</h1>
           <div id="div2_anchor"></div>
</div>
<div class="div2">This is the div that is being overlapped by the nav</div>

I would debug this code by giving the #div2_anchor a widht and height and a background color, that way you will be able to see exactly where it sits on the page. There may be a more sensible way around this! But this is what I came up with.

Hey! Thanks for your reply! Yes. One of the things i thought would do it is to create this "ghost element", which I thought was just plain wrong. Fortunately, as I was working in Wordpress I got it to work by just fixing some sections. although I asked a programmer friend of mine and he said he would do it in Javascript... Anyone know a good way to do this in Javascript, feel free to share!!