Search code examples
htmlcsshyperlinknav

anchor element linking to another section of the same page jumps too far down


HTML:

<nav id="nav-bar">
         <ul>
          <li><a class="nav-link" href="#features">Features</a></li>
          <li> <a class="nav-link" href="#how-made">How They Are Made</a></li>
          <li> <a class="nav-link" href="#pricing">Pricing</a></li>
        </ul>
</nav>

CSS:

 nav > ul {
  display: flex;
  justify-content: space-between;
  align-items: center;

}

li {
  margin: 20px;
  list-style: none;
}

 a {
  color: #000;
  text-decoration: none;
}

When I click on the link in the Nav bar that is fixed on top, it jumps down to the right area but it seems to jump too far down cutting off the top of the section I'm jumping too.

My nav-bar is apart of header that has this code set to it

CSS:

#header-img{
  width: 100%;
  max-width: 200px;
  max-height: 400px;
}

#header{
  display: flex;
  width: 100%;
  top: 0;
  align-items: center;
  margin-bottom: 20px;
  justify-content: space-between;
  Position: fixed;
  background-color: white;
}

Solution

  • Try 'scroll-padding-top' CSS property:

    html {
      scroll-padding-top: 100px; <-- replace with height of your position: fixed navbar
    }
    

    https://getpublii.com/blog/one-line-css-solution-to-prevent-anchor-links-from-scrolling-behind-a-sticky-header.html