aaronweber
aaronweber

Reputation: 205

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.

Upvotes: 18

Views: 35088

Answers (5)

iwiick
iwiick

Reputation: 581

Well. I had this issue as well. The best and fastest solution I could find here is to use the following code snippet in your Style tag or CSS file.

html
{
  scroll-padding-top: 12vw; /* height of sticky header */
}

Upvotes: 26

Nealio
Nealio

Reputation: 21

This worked for me.

:target {
    display: block;
    position: relative;
    top: -100px;
    visibility: hidden;
}

Upvotes: 2

Bryan
Bryan

Reputation: 41

I find both answers together provides the most robust solution across multiple browsers. I include both in my CSS...

a[name]:not([href]) {
    padding-top: 90px;
    margin-top: -90px;
}
a[name]:not([href]):before {
    display: block;
    content: " ";
    padding-top: 90px;
    margin-top: -90px;
    visibility: hidden;
}

Upvotes: 2

jstice4all
jstice4all

Reputation: 1938

@Daniel Imms solution is good but if headers had top margin it would be reset by this negative top margin. I found a solution that uses pseudoclasses:

h2:before {
    display: block;
    content: " ";
    height: 20px;  /* Give height of your fixed element */
    margin-top: -20px; /* Give negative margin of your fixed element */
    visibility: hidden;
}

Thus this doesn't reset original top-margin.

Upvotes: 9

Daniel Imms
Daniel Imms

Reputation: 50149

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

jsFiddle

h2 {
    padding-top: 70px;
    margin-top: -70px;
}

Upvotes: 45

Related Questions