Blog

Thoughts from my daily grind

Fix Content Under Menu on Anchor Link Navigation

Posted by Ziyan Junaideen |Published: 18 March 2022 |Category: The Client Side
Default Upload |

Anchor links are links linking to different parts of the same page. They are useful for navigating visitors to different parts of the page. When a user clicks a link, it is important that the user sees the content the user expects to see.

Anchor links by default scroll the user so that the anchored content is on top of the viewport. If there is a floating menu, the content will hide under the menu. Fortunately, we can mitigate this issue with CSS.

<nav class="....">...</nav> <!-- height: 60px -->

<ul>
  <li><a href="#chapter-1">Chapter 1</a></li>
  <li><a href="#chapter-2">Chapter 2</a></li>
  <li><a href="#chapter-3">Chapter 3</a></li>
</ul>

<div id="chapter-1" class="post-chapter">...</div>
<div id="chapter-2" class="post-chapter">...</div>
<div id="chapter-3" class="post-chapter">...</div>

When the user clicks on "Chapter 1" the user will find the first 60px of div#chapter-1 under the menu. We can set the scroll-margin-top parameter to address this. If the menu is 60px, we may need to add extra so that the content won't be touching the menu.


.post-chapter {
    /* the original styles */

    scroll-margin-top: 100px;
}

Now your anchor links, linking to div.post-chapter will have enough headroom so that it won't be under the menu.

I hope this helped you with your frontend issues.

References

1MDN scroll-margin-top
2CSS Tricks - scroll-margin

About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments