How to make page anchors work correctly when there is a fixed header

Having a fixed header is very popular. It lets you keep you branding logo and navigation easily accessible to users even when they have scrolled down to read your article.

Have you tried to put anchor links on the page and then find that the scrolled to location is behind the fixed header? This is very common and very frustrating.

I recently faced this issue. Several searches and several answers were not helpful or just really bad. I finally found one that was pretty good, Fixed page header overlaps in-page anchors, however, it didn’t account for having a different sized header for different devices.

My solution is to use javascript & jQuery to get the height of the fixed header and the add some css to the page.

        // scroll the page relative to :target with jQuery:
        var headerHeight = $("#myIDofMyHeader").height();
        var cssString = '<style> :target::before { content: \"\"; display: block; height: ' + headerHeight + 'px; margin: -' + headerHeight + 'px 0 0; }</style>';

This worked great for me and I hope it works great for you or possibly gets you most of the way to your solution!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.