0
votes

When styling the navbar in Bootstrap 4, I have a drop down. I want to highlight the dropdown item when it is active. However, when I use the 'active' class, all sub-items (children) get the highlight effect also. This looks ugly. In the attached sample, I don't want 'Link dd1' and 'Link dd2' to be highlighted.

How can I highlight the parent menu item only without the sub-items? Thank you all.

Fiddle with code sample

Code:

<style>
#x
 .active a{color:yellow ; background-color:brown;}

</style>
<nav id="x" class="navbar navbar-expand-sm bg-dark navbar-dark">
  <a class="navbar-brand" href="#">Logo</a>
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Link 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link 2</a>
    </li>

    <!-- Dropdown -->
    <li class="nav-item dropdown active">
      <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
        Dropdown link
      </a>
      <div class="dropdown-menu">
        <a class="dropdown-item" href="#">Link dd1</a>
        <a class="dropdown-item" href="#">Link dd2</a>
      </div>
    </li>
  </ul>
</nav>
<br>

<div class="container">
  <h3>Navbar With Dropdown</h3>
  <p>This example adds a dropdown menu in the navbar.</p>
</div>
1

1 Answers

1
votes

The reason why all the sub-items are highlighted as well is because you told it so via CSS:

#x .active a {
    color:yellow; 
    background-color:brown;
}

You're saying please highlight all the anchor tags on the active menus.

If you only want to highlight the parent menu, just be specific:

#x .active a.nav-link {        
    color:yellow; 
    background-color:brown;
}

demo: https://jsfiddle.net/davidliang2008/aq9Laaew/285539/

or even

#x .active > a {        
    color:yellow; 
    background-color:brown;
}

demo: https://jsfiddle.net/davidliang2008/aq9Laaew/285541/

will do the job.