Bootstrap 5 Scrollspy

Scrollspy

Scrollspy is used toScrollThe navigation list links are automatically updated.

How to Create Scrollspy

How to Create Scrollspy

The following example shows how to create a Scrollspy:

Example
<!-- Scrollable area -->
<body data-bs-spy="scroll" data-bs-target=".navbar" data-bs-offset="50">
<!-- Navigation bar - <a> elements are used to jump to a certain part of the scrollable area -->
</div>
  <nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
    <ul class="navbar-nav">
    </div>
<li><a href="#section1">Section 1</a></li>
</nav>
<div id="section1">
  <!-- Section 1 -->
  <h1>Section 1</h1>
<p>Please try scrolling this page and check the navigation bar while scrolling!</p>
</div>
...

</body>

Try it yourself

Explain the example data-bs-spy="scroll" Add to the element used as the scrollable area (usually <body> element).

Then add data-bs-target attribute, whose value is id or the class name of the navigation bar (.navbar). This is to ensure that the navigation bar is connected to the scrollable area.

Please note that the scrollable elements must match the link ID within the navigation bar list item (<div id="section1"> Matching <a href="#section1">)

Optional data-bs-offset The attribute specifies the number of pixels from the top that are offset when calculating the scroll position. It is useful when the navigation bar links jump to scrollable elements and you feel that the active state changes too early. The default value is 10 pixels.

Relative positioning is required: Elements with data-bs-spy="scroll" require CSS Position The value of the attribute must be set to "relative" for it to work properly.