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.
You can do this by setting position: relative;
on the target <a>
element; just give the header a set height, and set top: -[header height]
on the <a>
.
Here's a JSFiddle. Click the Link
at the top of the long page (please excuse the vast amount of Lorum Ipsum). The page will jump down to the red title.
body {
margin-top: 20px; /* Same height as header */
}
#header {
position: fixed;
background: black;
color: white;
height: 20px;
line-height: 20px;
width: 100%;
top: 0;
}
h3 a {
position: relative;
top: -20px; /* Negative header height */
/* Don't select anchor */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
<a>
is offset from the containing element (<h3>
in this case), user selection is disabled with user-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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With