DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How To Not Cut Off The Top Of Your Section When Using Anchor Tags
Julia πŸ‘©πŸ»β€πŸ’»
Julia πŸ‘©πŸ»β€πŸ’»

Posted on • Updated on • Originally published at community.codenewbie.org

How To Not Cut Off The Top Of Your Section When Using Anchor Tags

When I created my personal portfolio, I used anchor tags in my sticky navigation bar to make it easy for readers to jump directly to the section they were interested in. But when working with a sticky navigation bar, the top of each section was cut off by the height of the navigation bar.

Preview of the problem

NEW APPROACH

Here's how I solved this problem

Add the scroll-margin-top property to the section and set the value equal to the height of the header.

/* style.css */

nav-bar {
  height: 20vh;
}

.section-id {
  scroll-margin-top: 20vh;
}
Enter fullscreen mode Exit fullscreen mode
<!-- index.html -->

<section id="section-id">
  <div>
    CONTENT
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

OLD APPROACH
Create an anchor tag directly under each section, give it a class, and add the following properties to it:

/* style.css */

nav-bar {
  height: 20vh;
}

.anchor {
  display: block;
  position: relative;
  top: -20px; /* this is your offset */
  visibility: hidden;
}
Enter fullscreen mode Exit fullscreen mode

The offset depends on the height of your navigation bar.

Your sections in your HTML file should look like this:

<!-- index.html -->

<section id="section-id">
  <a class="anchor" id="anchor-id"></a>
  <div>
    CONTENT
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

If you want to take a look at my website πŸ‘‰ https://julia-undeutsch.netlify.app/


Thank you

Thanks for your reading and time. I really appreciate it!

Top comments (2)

Collapse
 
fchaussin profile image
François CHAUSSIN

This solution is great, but do you know the scroll-margin-top property? It is working according to your nav-bar height when on position: sticky. And solve the problem in a more consistent way.
Cheers

Collapse
 
yuridevat profile image
Julia πŸ‘©πŸ»β€πŸ’» Author • Edited on

Thank you. I will update the article immediately :)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: