Offsetting anchor hash tag links to adjust for fixed header

Sometimes our website has a fixed header or navigation menu that usually remains fixed at the top of the page. When you use the URL anchor (the #fragment part), the browser window will scroll itself (instantly) to bring anchor at the top of the page, leaving the content behind the fixed header. So here we need for offsetting anchor hash tag links to adjust for fixed header to let content appear below the fixed item.

Offsetting anchor to adjust for fixed header

VIEW DEMO

The solution might be useful in cases:

  • When you refer a particular section in a page from another page or
  • In page navigation, when you link to an anchor elsewhere in the page

In either case we just have to apply some offsetting to anchor hash tag links to let itself adjust for fix header and there is a very simple CSS rule to obtain this.

Offsetting anchor hash tag links to adjust for fixed header

HTML:

CSS:

Quite simple? We are using :before pseudo element and giving it a height, which pushes up the size of the header, then use negative margin to yank it back up into place. VIEW DEMO

You Might Interested In

17 COMMENTS

  1. Qqx Adrian says:

    You can even do it without the .offset class by just using :target pseudoclass selector, like so:

    :target::before {
    }

    Reply
  2. vKrue says:

    Thank you so much. I’ve seen many other solutions to this problem. I have a list of anchors and when I applied the usual padding or margin solutions as suggested on other sites it spaced ALL of the items in the list apart from one another on the page, not what I wanted.

    This “offset” class works wonderfully.

    Thank you again

    Victor Krueger – Beginning Web Designer

    Reply
  3. Amit Sonkhiya says:

    Hi Blario

    Your issue may appear due to some other code in your page. Please inspect that carefully and still if you are unable to find, you can mention us the link.

    Thanks

    Reply
    1. Amit Sonkhiya says:

      Hi Blario,

      Your issue may appear due to some other code in your page. Please inspect that carefully and still if you are unable to find, you can mention us the link.

      Thanks

      Reply
          1. Sean says:

            Figured out the solution — add the following to the offset class:

            position: relative;
            vertical-align: top;
            z-index: -1; /* This prevents any links being behind the offset block and un-clickable */

            You also may need to bring the z-index of the navigation menu to the top:
            z-index: 999999;

            Hope this helps!

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.