7

I have a sticky header that floats over the rest of the page. When I link to page anchors, of course is scrolls so that the anchor is at the top of the page. However, when this happens the header covers up the text beneath.

Is there someway to fix this? I can't just move the anchor down because there are many of them on the page and each one has a different amount of text following. My first though was to somehow scroll to some height above the anchor.

Thanks, David

hoytdj
  • 155
  • 3
  • 13
  • Not without JavaScript, I think. – David Thomas May 18 '12 at 21:47
  • Not necessarily the best approach, but if your layout/design allows it, you could give the anchor a padding-top equal to the height of the header. – Steve May 18 '12 at 21:54
  • exactly what I was about to say, though it depends how high your header is... – Yoav Kadosh May 18 '12 at 21:56
  • You could always be 'that guy' and have the actual content in a frame below the sticky footer, but this is going to open up a host of other issues you'd definitely rather not deal with. http://www.yourhtmlsource.com/frames/goodorbad.html – Gordon Gustafson May 18 '12 at 21:56

2 Answers2

4

The :target pseudo element could be what you are looking for. With :target you can address the element that is pointed out with the #-mark. Read more about it here

albinohrn
  • 626
  • 3
  • 8
  • The :target selector looks like it might be what I want. But, then how can I make the window move down with just CSS? I can use javascript of course but I'd rather not. – hoytdj May 19 '12 at 21:09
  • The page will scroll down just like it did before, but now with the :target selector you add some extra padding to push the element down. So that it is no longer hidden by the sticky header. – albinohrn May 20 '12 at 10:13
  • I saw so many complicated solutions for such a simple problem, and just targeting only `:target` (rather than `:target::before` as I saw many places) was the best solution for me. In my case I inserted a separator between each heading, and actually have my anchor point to the separator to add even a little more room. Was getting a little funky behavior (where not every element was padding properly) but seemed to solve my issue (despite my solution being a touch hacky). Thanks for the great tip. – twknab Jul 26 '18 at 07:05
0

I ran into the same issue, ended up making a rule like this:

A.named:target {
    display: inline-block;
    height: 120px;
    margin-top: -120px;
}

I then applied the class "named" to any anchor tag that I want the browser to scroll to. This adds 120px of space between the top of the browser and the bottom of the element that contains the anchor - about 80px for the header, and another 40px to compensate for the height of the H2 headings I was linking to... And, with the negative margin cancelling out the positive one, it doesn't affect the look of my page.

Hope this helps!

Ben
  • 1