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 | | ... | | ... | +---------------------------------+ +---------------------------------+
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.
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.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With