Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed position navbar obscures anchors [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 318
Matt Dryden Avatar asked May 24 '12 07:05

Matt Dryden


People also ask

How do I stop anchor links from scrolling behind sticky?

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 I change the position of an anchor tag in HTML?

You have to give your anchor a the rule display: block; . Anchors are inline elements per default. If you give an element position: absolute , you take it out of so-called normal document flow.


2 Answers

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 73
Jan Avatar answered Oct 16 '22 16:10

Jan


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 24
Alexander Savin Avatar answered Oct 16 '22 17:10

Alexander Savin