Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed page header overlaps in-page anchors

Tags:

html

url

anchor

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://example.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    | | ...                             |      | ...                             | +---------------------------------+      +---------------------------------+ 
like image 660
Tomalak Avatar asked Nov 03 '10 10:11

Tomalak


People also ask

How do you prevent anchors from scrolling behind a sticky header?

You could add the scroll-padding-top CSS property to an HTML element with a value of 4rem . Now when you click the anchor link, the browser jumps to the anchor section but leaves padding of 4rem at the top, rather than scrolling the anchor point all the way to the top.

How do you fix a fixed header position?

Answer: Use CSS fixed positioning You can easily create sticky or fixed header and footer using the CSS fixed positioning. Simply apply the CSS position property with the value fixed in combination with the top and bottom property to place the element on the top or bottom of the viewport accordingly.


2 Answers

If you can’t or don’t want to set a new class, add a fixed-height ::before pseudo-element to the :target pseudo-class in CSS:

:target::before {   content: "";   display: block;   height: 60px; /* fixed header height*/   margin: -60px 0 0; /* negative fixed header height */ } 

Or scroll the page relative to :target with jQuery:

var offset = $(':target').offset(); var scrollto = offset.top - 60; // minus fixed header height $('html, body').animate({scrollTop:scrollto}, 0); 
like image 74
Adrian Garner Avatar answered Sep 28 '22 20:09

Adrian Garner


I had the same problem. I solved it by adding a class to the anchor element with the topbar height as the padding-top value.

<h1><a class="anchor" name="barlink">Bar</a></h1> 

I used this CSS:

.anchor { padding-top: 90px; } 
like image 28
mutttenxd Avatar answered Sep 28 '22 20:09

mutttenxd