Highlighting the active nav-item in Bootstrap-5 is proving to be a challenge

I'm having trouble with the Bootstrap navbar. I want to change the color of the active nav-link, but it's not working as expected. I am currently using Bootstrap-5.

Below is the CSS code I have:

.nav-link {
    color: #666777;
    font-weight: 400;
}

.nav-link.active {
    color: red;
}

.nav-link:hover {
    color: #000;
}

Here is the HTML code:

<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43212c2c37303731223303766d706d70">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="/styles.css" rel="stylesheet">
        <title>My Webpage</title>
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <a class="navbar-brand" href="/index.html">My Webpage</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                  <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                      <a class="nav-link" href="/index.html">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="/about.html">About</a>
                    </li>
                    <li class="nav-item dropdown">
                      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Hobby
                      </a>
                      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="/hobby/anime.html">Hobby1</a>
                        <a class="dropdown-item" href="/hobby/books.html">Hobby2</a>
                        <a class="dropdown-item" href="/hobby/vtubers.html">Hobby3</a>
                      </div>
                    </li>
                  </ul>
                </div>
              </nav>
        </header>
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f6f706f6f7a6d31756c5f2e312e29312f">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a3aeaeb5b2b5b3a0b181f5eff5eff0">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    </body>
</html>

When I change the href in the tag to "#", for example:

<a class="nav-link" href="/about.html">About</a> to <a class="nav-link" href="#">About</a>
, the color changes when clicked but the navigation doesn't work.

I also attempted to manually add the class .active to the appropriate nav-link in each file, but that also didn't solve the issue.

Any help would be greatly appreciated.

Answer №1

It appears that you are utilizing Bootstrap 5, yet your HTML file contains Bootstrap 4 scripts. This inconsistency could be the root cause of the issues you're experiencing. To properly navigate users to another page, consider specifying the file location directly instead of using a generic placeholder like "#". For example, use something like "./nextPage.html". Hopefully, this adjustment will resolve the problem for you.

Answer №2

Your code has multiple issues that need to be addressed.

  1. When using the Bootstrap CDN, it is important to include both the CSS and script links. However, in your code, the CSS version is 5.3.3 and the script version is 4.3, causing a mismatch that needs to be corrected.
  2. If you wish to override any Bootstrap property, always remember to add !important to the CSS.

Below is the corrected code with all the issues fixed:

.nav-link {
    color: #666777 ;
    font-weight: 400;
}

.nav-item .active {
    color: red !important;
}

.nav-link:hover {
    color: #000;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf9f4f4efe8efe9faebbaaeb1bcb1be">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyzxPEjISv5WaRU9OFeRpoj6Ybtn7mD5pNzyT2bRjXh0JMhjY6hW+ALrwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9e9393888f888e9d8cbcb6c9c4c9c8">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tYslHB60NNkcl6s9fDVLLSaAX5NDzOxh9GkcldsmsleolyN6jIeHz" crossorigin="anonymous"></script>

<header>
            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <a class="navbar-brand" href="/index.html">My Webpage</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                  <ul class="navbar-nav mr-auto">
                    <li class="nav-item">
                      <a class="nav-link active" href="/index.html">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="/about.html">About</a>
                    </li>
                    <li class="nav-item dropdown">
                      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Hobby
                      </a>
                      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="/hobby/anime.html">Hobby1</a>
                        <a class="dropdown-item" href="/hobby/books.html">Hobby2</a>
                        <a class="dropdown-item" href="/hobby/vtubers.html">Hobby3</a>
                      </div>
                    </li>
                  </ul>
                </div>
              </nav>
        </header>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on optimizing a setTimeout script for seamless integration with an HTML form

Here is the script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function addToCart() { document.getElementById("msgs-box").innerHTML = "Item added to cart s ...

Animate the menu as you scroll

I am attempting to create a jQuery top menu that adjusts its height based on the window scroll position. Using $(selector).css("height", "value") works fine, but when I try to animate it, it doesn't behave correctly. Here is my code. Thank you for you ...

What is the best way to ensure one div expands to full width while simultaneously hiding another div on the page?

Hey there, I'm looking for a way to expand the width of a clicked div while making the other div disappear from the screen simultaneously. It should also be toggleable, so clicking the button again will shrink the div and bring back the other one. For ...

CSS page rule option for optimal display in Safari

What is the workaround for using alternative rules in Safari? I am currently implementing the angularPrint directive to enable print functionality on certain pages. This directive includes some helper classes in my document and utilizes the @page direct ...

XAMPP's main directory

I have been struggling with this dilemma for quite some time, tirelessly searching for a solution. <img src="/images/test.jpg" /> This code snippet fetches an image from the root path, particularly in my case when it's live on a LAMP server. ...

Can a YouTube video be triggered to play when a specific CSS style is selected?

I am searching for a method to display and play different YouTube videos based on a selected CSS style from a drop-down menu. I believe JavaScript can be utilized to detect the chosen CSS. Include the following in the html header of the page. <script ...

What causes my code to break completely when I import something?

My chrome extension has a simple function that retrieves a user's selected text using the Chrome Tabs API. I am looking to integrate a Hugging Face API in the future, but I am facing an issue. Whenever I try to import the necessary model, the Chrome T ...

"Learn the process of connecting an HTML5 element to Angular 2 source code while in a saving mode

In this Angular2 implementation, I have created some HTML code for user access. However, I am facing an issue where the data is not binding at the Angular2 source code side. HTML Code <form class="form-horizontal" novalidate [formGroup]="EmployeeForm" ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Unique CSS animation effect for mouse hover interaction

I am working with a set of buttons that have an animation named "slideIn". The keyframes for this animation are as follows: @keyframes slideIn { 0% {opacity: 0; transform: translate(-200px);} 100% {opacity: 1; padding-left: 110px; w ...

Steps for linking a page to a modal without embedding the page's content within the modal

Here is a snippet of code for a modal (from Twitter Bootstrap) that I am currently working with: <!-- Large Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large Modal</button&g ...

Having difficulty uploading files to my website [PHP]

I'm having trouble with a PHP tutorial I followed for uploading an image. Despite my best efforts, the upload always fails and I can't figure out why. I've rewritten the code multiple times but the problem persists. The goal of this code is ...

Update the content retrieved through ajax periodically

Looking to set up a periodic update for this ajax fetch function, say every 10 seconds. I've tried a few approaches but none seem to work as expected. That's why I'm reaching out here for help. So, any idea how I can refresh the content ev ...

What orientation is best for the back arrow to take in a website written in Arabic?

Currently developing a website that supports Arabic language while considering security measures. The browser's back button will terminate the session, requiring users to utilize the on-page back button instead. When incorporating Arabic text, should ...

Tips for showing the value in the subsequent stage of a multi-step form

Assistance is required for the query below: Is there a way to display the input field value from one step to the next in multistep forms? Similar to how Microsoft login shows the email in the next step as depicted in the image below: https://i.sstatic.ne ...

Text positioned on the right side of the image, appearing to hover above

After finding a helpful example on Stack Overflow, I successfully implemented a similar layout for product boxes in a JSFiddle. I then replicated the CSS and HTML almost exactly on my Wordpress blog, but encountered an issue where the title, description, a ...

HTML: Launch Frameset in a Separate Tab or Window

I have encountered an issue with using FRAMESET. Situation: Within my frameset, I have a menu with 5 links. When I click on the home page, everything looks fine. However, when I open it in a new tab or window, the design is not displayed. Is there a way ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Locator for finding compound text within a div class using Selenium WebDriver

I am struggling to select a specific button in the UI that shares similarities with other elements. Below is the code snippet for the button in question: <div class="ui green ok inverted button"> <i class="checkmark icon"></i> Yes </d ...

Placement of the Zend submit button

How can I position the submit button at the bottom of a form wrapped in an HTML table, when calling two forms from the same controller? Currently, the button is stuck between the first form and the table. I attempted to assign the element in my controller ...