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.
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.
Add a custom anchor To add an anchor to a heading in HTML, add a <section> element with an id attribute. Don't use <a name> . Use lowercase for id values, and put hyphens between words. To add an anchor to a heading in Markdown, add the following code to the end of the line that the heading is on.
Position your cursor where you want the anchor placed. Typically, this is the main content point in your page, like a sub-heading. Click the "Insert/edit anchor" icon in the WYSIWYG editor. Enter a short Anchor Id (name) that describes the target anchor.
I found this solution:
<a name="myanchor"> <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1> </a>
This doesn't create any gap in the content and anchor links works really nice.
You could just use CSS without any javascript.
Give your anchor a class:
<a class="anchor" id="top"></a>
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
a.anchor { display: block; position: relative; top: -250px; visibility: hidden; }
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