Search code examples
htmluser-interfacehyperlink

How to make Fragment Identifier point to more accurate anchor on page?


I'm using fragment identifier links within my navigation menu, inside a simple static website, and they are pointing to the wring place, or more accurately, just a little off the right place.

That is, all the links seem to point to an anchor that is a little off where I want to point it to. They all point about 2-4 lines below what would be optimal for the UI. It always looks like the section's heading is cut off at the top.

Is there any fix that can help me get these fragment identifier links to point about 2-4 lines above where they're being anchored to now?

How does everyone else deal with this?

Note: In the nav menu I'm using:

href="#menuItemX"

and in the anchor I'm using:

id="menuItemX"

And I've been using a Chrome browser.


Solution

  • Simply use the scroll-margin-top css property

    #menuItemX {
       scroll-margin-top: 3em;/*change*/
    }
    

    Or, you can use javascript to do it once and for all:

    document.querySelectorAll('a[href^="#"]').forEach(a=> {
        a.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href').substring(1);
            const targetElt = document.getElementById(targetId);
            window.scrollTo({
                top: targetElt.offsetTop - 48, // change
                behavior: 'smooth'
            });
        });
    });