Adding an automatic offset to the scroll position for all hash-links/calls

I found this way of adding a :before in the css seems to work well.

h2:before { 
  display: block; 
  content: " "; 
  margin-top: -285px; 
  height: 285px; 
  visibility: hidden; 
}

More at CSS Tricks website


I actually found a solution myself that worked for me, using only css:

I added a margin-top: -40px; and padding-top: 40px; to the element that the jump-link was pointing to. This works for all major browsers: IE (7-9), Firefox, Opera, Chrome and Safari.

Only problem: In case that this element is after a floated element, the negative margin doesn't work (meaning the positive padding becomes visible). Please comment, if anyone knows a solution/workaround for this. I'll update my post then. Thank you!


To add to the solution on this, I found that setting the display to none solved the issue of padding being visible when used amongst floated elements.

So:

.symbol-target {
    padding-top: 40px;
    margin-top: -40px;
    width: 1px; /* '0' will not work for Opera */
    display: hidden;
}

I also included this style as an empty div right above my target content.


Nowadays in 2021 there's a nice simple only-css solution with :target and scroll-margin-top

:target {
    scroll-margin-top: 100px;
}

It works in all major browsers

References:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-top
  • https://developer.mozilla.org/en-US/docs/Web/CSS/%3Atarget