How do I keep a fixed-top navbar from overlapping anchor targets when using ScrollSpy?
Asked on Jun 03, 2025
1 Answer
When using a fixed-top navbar with Bootstrap's ScrollSpy, you can prevent it from overlapping anchor targets by adding a top padding to the body or the element containing the scrollable content. This padding should match the height of the navbar.
<!-- BEGIN COPY / PASTE -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<a class="navbar-brand" href="#">Brand</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#section1">Section 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section2">Section 2</a>
</li>
</ul>
</div>
</nav>
<div data-bs-spy="scroll" data-bs-target=".navbar" data-bs-offset="70" class="scrollspy-example" tabindex="0">
<div id="section1" style="padding-top: 70px;">Section 1 content...</div>
<div id="section2" style="padding-top: 70px;">Section 2 content...</div>
</div>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- The `fixed-top` class is used to fix the navbar at the top.
- Add `data-bs-offset="70"` to the scrollable element to account for the navbar height.
- Ensure each section has a `padding-top` equal to the navbar height (e.g., 70px) to prevent overlap.
- Adjust the `padding-top` value if your navbar's height changes.