This question already has an answer here:
- Fixed page header overlaps in-page anchors 28 answers
I am trying to clean up the way my anchors work. I have a header that is fixed to the top of the page, so when you link to an anchor elsewhere in the page, the page jumps so the anchor is at the top of the page, leaving the content behind the fixed header (I hope that makes sense). I need a way to offset the anchor by the 25px from the height of the header. I would prefer HTML or CSS, but Javascript would be acceptable as well.
My solution combines the target and before selectors for our CMS. Other techniques don't account for text in the anchor. Adjust the height and the negative margin to the offset you need...
You could just use CSS without any javascript.
Give your anchor a class:
You can then position the anchor an offset higher or lower than where it actually appears on the page, by making it a block element and relatively positioning it. -250px will position the anchor up 250px
how about hidden span tags with linkable IDs that provide the height of the navbar:
heres the fiddle: http://jsfiddle.net/N6f2f/7
Instead of having a fixed-position navbar which is underlapped by the rest of the content of the page (with the whole page body being scrollable), consider instead having a non-scrollable body with a static navbar and then having the page content in an absolutely-positioned scrollable div below.
That is, have HTML like this...
... and CSS like this:
This achieves the desired result in a straightforward, non-hacky way. The only difference in behaviour between this and some of the clever CSS hacks suggested above are that the scrollbar (in browsers that render one) will be attached to the content div rather than the whole height of the page. You may or may not consider this desirable.
Here's a JSFiddle demonstrating this in action.
Here's the solution that we use on our site. Adjust the
headerHeight
variable to whatever your header height is. Add thejs-scroll
class to the anchor that should scroll on click.I added 40px-height
.vspace
element holding the anchor before each of myh1
elements.In the CSS:
It's working great and the space is not chocking.