If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:
Is there a way to use the URL anchor (the #fragment
part) to have the browser scroll to a certain point in the page, but still respect the height of the fixed element without the help of JavaScript?
http://foo.com/#bar
WRONG (but the common behavior): CORRECT: +---------------------------------+ +---------------------------------+ | BAR///////////////////// header | | //////////////////////// header | +---------------------------------+ +---------------------------------+ | Here is the rest of the Text | | BAR | | ... | | | | ... | | Here is the rest of the Text | | ... | | ... | +---------------------------------+ +---------------------------------+
I use this approach:
It adds an invisible element before each target. It works IE8+.
Here are more solutions: http://nicolasgallagher.com/jump-links-and-viewport-positioning/
Implemented using
:before
worked great until we realized that the pseudo element was actually covering and blocking pointer events that sat within the pseudo element's area. Using something likepointer-events: none
on the:before
or even directly on the anchor had no affect.What we ended up doing was making the anchor's positioning absolute and then adjusting it's position to be the offset/height of the fixed area.
Offset Anchor without Blocking Pointer Events
The value with this is that we're not blocking any elements that might fall within those 300px. The downside is that grabbing that element's position from Javascript needs to take into account that offset so any logic there had to be adjusted.
You could try this:
Set the top padding value to the actual height of your header. This will introduce a slight extra gap at the top of your header, but it will only be visible when the user jumps to the anchor and then scrolls up. I've made up that solution for my site right now, but it only shows a small fixed bar at the top of the page, nothing too high.
I'm using @Jpsy's answer, but for performance reasons I'm only setting the timer if the hash is present in the URL.
I use this method because for some reason, none of the other solutions proposed actually worked for me. I promise I tried.
Replace section by a class if you prefer.
source: Jump links and viewport positioning
For those who do not believe me I kindly prepared a jsfiddle with the solution in it: SOLUTION
Add a class with a "paddingtop", so it works ;)
And for css you have: