Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offsetting Anchor Links with Fixed Header

There've been a few similar posts (offsetting an html anchor to adjust for fixed header, for example), but those solution doesn't work for my particular case.

I am using jQuery to populate a Table of Contents, specifically the method described here: http://css-tricks.com/automatic-table-of-contents/. It searches for the h2 tags within the article, and then creates anchors links.

The problem is I'm using a fixed header. When I click on one of these anchor links, the target h2 is underneath the header. One temporary solution I'm using is:

h2:target{
  padding-top:[header-height];
}

This works until you scroll back up, and there's a huge gap in the middle of the content. Do y'all have any ideas on how I can offset these anchor links to account for the header? I'd like to keep the HTML as semantic as possible. Any help would be appreciated.

Here's a jsFiddle of what exactly I'm talking about: http://jsfiddle.net/aweber9/GbNFv/

Thanks.

like image 866
aaronweber Avatar asked Mar 31 '13 05:03

aaronweber


People also ask

How do you prevent anchors from scrolling behind a sticky header?

You could add the scroll-padding-top CSS property to an HTML element with a value of 4rem . Now when you click the anchor link, the browser jumps to the anchor section but leaves padding of 4rem at the top, rather than scrolling the anchor point all the way to the top.

What is offset anchor?

The offset-anchor CSS property specifies the point inside the box of an element traveling along an offset-path that is actually moving along the path.

How do you add an anchor to a header?

To add an anchor to a heading in HTML, add a <section> element with an id attribute. Don't use <a name> . Use lowercase for id values, and put hyphens between words.

How do I stop my anchor from clicking?

To disable a HTML anchor element with CSS, we can apply the pointer-events: none style. pointer-events: none will disable all click events on the anchor element.


1 Answers

You could include padding-top and then use negative margin-top to balance it out.

jsFiddle

h2 {
    padding-top: 70px;
    margin-top: -70px;
}
like image 81
Daniel Imms Avatar answered Oct 12 '22 02:10

Daniel Imms