Advertisement

Google Ad Slot: content-top

Bootstrap 5 Scrollspy


Scrollspy in Bootstrap 5 is used to automatically update navigation links based on scroll position. It works with navigation components like .nav or .list-group, and it's often used to highlight the active link in a sidebar or navbar as you scroll through a page.

Scrollspy:

  • A scrollable container (or the body) with the data-bs-spy="scroll" attribute.
  • A target navigation using the data-bs-target attribute to specify which navigation to update.
Example
<body data-bs-spy="scroll" data-bs-target=".navbar" data-bs-offset="50">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
<div class="container-fluid">
<ul class="navbar-nav">
<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>
<li class="nav-item">
<a class="nav-link" href="#section3">Section 3</a>
</li>
</ul>
</div>
</nav>
<div id="section1" class="container-fluid text-bg-primary" style="padding:100px 20px;">
<h1>Section 1</h1>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
</div>
<div id="section2" class="container-fluid text-bg-secondary" style="padding:100px 20px;height:200px">
<h1>Section 2</h1>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
</div>
<div id="section3" class="container-fluid text-bg-info" style="padding:100px 20px;">
<h1>Section 3</h1>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
<p>Try to scroll this section and look how the section is navigate while scrolling! Try to scroll this section and look how the section is navigate while scrolling!</p>
</div>
</body>
Try it yourself

Key Attributes

data-bs-spy="scroll": Enables scrollspy functionality.

data-bs-target="#id": Specifies the navigation element to update.

data-bs-offset="number": Adjusts the scroll offset for updating the active link (default is 10).