I ran into an issue recently where I wanted to use anchors to jump to different sections within a long web page. The problem was every time I clicked the page would jump, but a fixed header would cover part of each section’s content.
After a bit of searching, some trial and error, a simple HTML adjustment and a bit of CSS and the problem was solved.
The Setup and the Problem
I started with a header that was set up like so: (styles inlined for clarification)
Near the top of the page was an unordered list that contains the anchor links:
<div class="header" style="position: fixed; top: 0;"></div>
<li><a href="#section1">Anchor Text</a></li>
<li><a href="#section2">Anchor Text</a></li>
<li><a href="#section3">Anchor Text</a></li>
And of course there was each section of content which I wanted to jump to:
<div class="section" id="section1"></div>
<div class="section" id="section2"></div>
<div class="section" id="section3"></div>
Now as you can see, I started with adding the IDs to each section. This is when I noticed that clicking on one of the anchor links would actually cause the page to jump to the right section, but some of the content in the section would get covered by the header which is fixed and stays at the top of the page when scrolling occurs.
To overcome the issue a minor HTML adjustment was made and a small amount of CSS was also added to bring it all together.
The Solution That Worked
First, I moved the id’s of each section to a new element: (a span in this case)
<span class="anchor" id="section1"></span>
<span class="anchor" id="section2"></span>
<span class="anchor" id="section3"></span>
The new <span> elements were added right above each section and would serve as the new anchor point. I’m not the biggest fan of empty elements on a page, but it does address the issue.
Once the new <span> elements were in place, a bit of CSS was added:
height: 115px; /*same height as header*/
margin-top: -115px; /*same height as header*/
The height and margin-top numbers are based on the height of the header. Using the Chrome developer tools, this number is easy to figure out.
After these simple adjustments, it was time to jump back in the browser and test it out. Clicking the anchor link jumped down the page and the <span> corrected the space for the header and voilà – The page now jumps correctly!