Active class in navbar

Bootstrap 5 Active class in navbar component

Responsive Active class in navbar built with Bootstrap 5. The active class allows you to move quickly and shows which part of the page you are currently in.


Basic example

To create an active class in navbar you need to use the scrollspy element.

Delete row and columns and if you don't need them, delete subsections.

Remove the .flex-column class to make the scrollspy horizontal and nest the scrollspy in the navbar.

If you use the .fixed-top class in the navbar element then in the spied element you should set data-mdb-offset="" - pixels to be offset from the top when calculating the scroll position (navbar height).

Section 1

...

Section 2

...

Section 3

...

Section 4

...
        
            
      <!-- Navbar -->
      <nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light">
        <!-- Scrollspy -->
        <div id="scrollspy1" class="sticky-top">
            <ul class="nav nav-pills menu-sidebar ps-2">
                <li class="nav-item">
                    <a class="nav-link" href="#example-1">Section 1</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#example-2">Section 2</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#example-3">Section 3</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#example-4">Section 4</a>
                </li>
            </ul>
        </div>
        <!-- Scrollspy -->
    </nav>
    <!-- Navbar -->

    <!-- Spied element -->
    <div 
      data-mdb-scrollspy-init
      data-mdb-target="#scrollspy1" 
      data-mdb-offset="59" 
      class="scrollspy-example" 
      style="margin-top: 41px;">
        <section id="example-1" class="text-white bg-primary ps-3">
            <h3>Section 1</h3>
            ...
        </section>
        <section id="example-2" class="text-white bg-info ps-3">
            <h3>Section 2</h3>
            ...
        </section>
        <section id="example-3" class="text-white bg-primary ps-3">
            <h3>Section 3</h3>
            ...
        </section>
        <section id="example-4" class="text-white bg-info ps-3">
            <h3>Section 4</h3>
            ...
        </section>
    </div>
    <!-- Spied element -->