How to fix HTML anchor link to scroll behind fixed header

Introduction

Fixed headers are with us for a long time already.

It's a pretty good feature because it improves the UI.

When user scrolls down, he is able to see the top header with the navigation menu and logo.

This way, he is able to navigate easily and not forced to scroll up to see the top menu.

Fixed header and HTML anchors problem

One issues which bothered me a lot, when a fixed ( or sticky ) header was activated, it was related to anchors.

Basically, when you scroll down to an anchor, the content was covered ( was behind ) the fixed header.

This was not looking good and it was a really bad user experience.

Please check the below image. If you have some anchors links at the top of the page, when an anchor link is clicked, the page jumps to the anchor. But, since the header is a fixed one, the anchor is behind the header and not visible.

fixed anchor behind fixed header

Fixing the anchors going behind the fixed header it is actually pretty simple. It is just a simple CSS code to be added to your stylesheet.

First of all you need to know the height of your header. If the height of your header is 100px, then you will need an offset of 120px maybe (to have some white space above the anchor).

After that, for all anchors on page, you will need to add a class ( like for example 'good-anchor' ).

Then, the last thing to do, it to add the below CSS code to your stylesheet:

.good-anchor {
    display: block;
    position: relative;
    top: -120px;
}

This will fix the anchor behind the fixed header.

fixed anchor scroll behind sticky header

Conclusion

I hope that you will find the presented tip useful. Don't forget to add the class to the anchor on the page, otherwise it will not work. If your anchor on page is a H, then add the class to it:

<h1 class="good-anchor">

That's it all.

Comments closed

Please contact me, if you have any questions or suggestions.