Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up an offset with anchor tags for a div

I have made a single page which has a navbar and with links pointing to section id in the page.

However, when I click on the link the section of the page scrolls down till the top of the section and due to my sticky navbar, the top part of my section goes behind it.

How do I create an offset height which would match my navbar height so that the div is visible at the right position?

Here is my a screenshot of what is happening.

Screenshot

Also, is there a way to smoothly scroll till the section? What is the easiest method to achieve this?

My example code:

HTML:

<nav>
  <ul>
    <li><a href="#section1">Section 1</a></li>
    <li><a href="#section2">Sction 2</a></li>
    <li><a href="#section3">Section 3</a></li>
  </ul>
</nav>


<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<div id="section3">Section 3</div> 
like image 356
Malika Singha Avatar asked Jan 29 '26 23:01

Malika Singha


1 Answers

Offsetting anchor hash tag links to adjust for fixed header

HTML :

<a href="#section1">Goto Section I</a>

<!-- Some more content -->


<h3 id="section1" class="offset">Section I</h3>

<p>Section specific content</p>

CSS:

.offset:before { 
    display: block; 
    content: " "; 
    height: 150px;      /* Give height of your fixed element */
        margin-top: -150px; /* Give negative margin of your fixed element */    
        visibility: hidden; 
}
like image 116
Sankalp Singha Avatar answered Jan 31 '26 13:01

Sankalp Singha