Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offsetting an html anchor to adjust for fixed header [duplicate]

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.

like image 367
Matt Dryden Avatar asked May 24 '12 07:05

Matt Dryden


People also ask

How do you prevent anchor links from scrolling behind a sticky header with one line in CSS?

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 anchor a header in HTML?

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.

How do you edit an anchor in HTML?

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.


2 Answers

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.

like image 35
Alexander Savin Avatar answered Oct 14 '22 21:10

Alexander Savin


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; } 
like image 192
Jan Avatar answered Oct 14 '22 19:10

Jan