I made a lengthy page that I’m testing on my computer. Since it’s so long, I added a table of contents to the top. Under the table of contents are some links that, when clicked, take you to a specific section of the page. Here’s an example of the markup I used:
<h4>Table of Contents</h4>
<ul>
<li><a href="#gotolink">Link</a></li>
</ul>
<h3><a name="gotolink">Link</a></h3>
<p>some stuff here</p>
It works fine. The problem is that I also have a fixed header, as in you always see the header no matter where you are on the page, and when I click a link under the table of contents it takes me to that section of the page but the header ends up covering the <h3> stuff. I want to make it so that when you click a link it takes you to that section of the page, but the section will be in the middle of your screen, not the top, so the header won’t cover anything.
Solution
You can do this by setting
position: relative;on the target<a>element; just give the header a set height, and settop: -[header height]on the<a>.Demonstration
Here’s a JSFiddle. Click the
Linkat the top of the long page (please excuse the vast amount of Lorum Ipsum). The page will jump down to the red title.CSS
Caveats
<a>is offset from the containing element (<h3>in this case), user selection is disabled withuser-select: none. This means that any text in the<a>isn’t selectable. This is why I didn’t wrap the<h3>‘s text in it in the JSFiddle demo.