How do I build a scrollspy-enabled sidebar that highlights headings?
Asked on Sep 06, 2025
1 Answer
To create a scrollspy-enabled sidebar that highlights headings, you can use Bootstrap's Scrollspy component. This feature allows you to automatically update navigation links based on scroll position.
<!-- BEGIN COPY / PASTE -->
<nav id="navbar-example3" class="navbar navbar-light bg-light flex-column align-items-stretch p-3">
<a class="navbar-brand" href="#">Navbar</a>
<nav class="nav nav-pills flex-column">
<a class="nav-link" href="#item-1">Item 1</a>
<a class="nav-link" href="#item-2">Item 2</a>
<a class="nav-link" href="#item-3">Item 3</a>
</nav>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="0" tabindex="0">
<h4 id="item-1">Item 1</h4>
<p>Content for item 1...</p>
<h4 id="item-2">Item 2</h4>
<p>Content for item 2...</p>
<h4 id="item-3">Item 3</h4>
<p>Content for item 3...</p>
</div>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- Ensure your sidebar links have href attributes that match the id of the content sections.
- Wrap your content in a container with the data-bs-spy="scroll" attribute and set the data-bs-target to the sidebar's id.
- Adjust the data-bs-offset attribute as needed to account for any fixed navigation bars.
- Make sure to include Bootstrap's CSS and JS files in your project for the scrollspy to function.