0

I'm trying a pure css approach to keeping the 'parent-most' navbar item highlighted when a child is clicked upon and a user navigates to that page. I have a primary navbar div with an unordered list, and each list has a list like so, so in this case a user navigates to the second most li here:

.primary-navbar ul li ul li{
    background-color: red !important;
}

how do I make it so when the second li is active, the first li has background color of blue?

I tried:

.primary-navbar ul li:active {
   background-color: blue !important
}

but that did not work and I'm not sure why. I'm trying to avoid jquery...

devdropper87
  • 3,215
  • 7
  • 30
  • 63
  • `:active` does not work that way, see [here](https://developer.mozilla.org/en-US/docs/Web/CSS/:active). It looks like you need to add your own active class. Also it would be helpful to see your HTML – cocoa Feb 01 '16 at 16:51
  • Sounds like you're looking for a CSS parent selector. [Have a look at this question](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector), as it may have an answer you're looking for. – Luuuud Feb 01 '16 at 17:20

1 Answers1

0

:active is the state of the element when active (i.e. a link is active when it is clicked). When you load the new page, no elements are active. You'll need to add a class to the li on the new page (something like 'active' or 'current-page' for example) to get the effect you're looking for. It's not possible with CSS only.

When you implement that, you should also take a second look at your CSS:

.primary-navbar ul li.active {
   background-color: blue !important
}

That will not only make the first (parent) li.active blue, it will also target any li.active nested beneath it. i.e. it will also make .primary-navbar ul li.active ul li.active blue.

Try something like:

.primary-navbar > ul > li.active {
   background-color: blue;
}

The >s will only target the li.active that is directly under the ul that is directly under .primary-navbar