ID: I202602281136
Status: idea
Tags: web development, website
scroll to header via nav
You can see it on the side of this website, a navigation bar that can scroll to headers. but how does it work?
Back in the days, you could do this with an <a> element with the name parameter. But as this thread answer says, name is deprecated. So how does it work now?
You first assign an ID to the elements a user can scroll to. If this is your h1 or h2, itād look something like this:
<h1 id="scroll-to-header-via-nav">scroll to header via nav</h1>
<h2 id="references">References</h2>This means that a link with a # will be able to navigate to your element. https://.../page.html#references would scroll to the 2nd element mentioned above.
So if you want to have a pagenav, the following will work:
<a href="#scroll-to-header-via-nav">scroll to header via nav</a>
<a href="#references">References</a>These 2 links would link to your headers if they are on the current page, cause the link will just add the # behind your url. Keep in mind that this might not work with some SPAās.
I have a sticky header in the way
If you have a header that is sticky which overlaps with your navigation, you can create an offset:
h1,
h2 {
scroll-margin-top: 100px;
}If you adjust the 100px to the height of your header, the page will scroll correctly.