I am trying to change the background color of one list item while there is another background color for other list items.
This is what I have:
<style type="text/css">
ul.nav li
{
display:inline;
padding:1em;
margin:1em;
background-color:blue;
}
.selected
{
background-color:red;
}
<ul class="nav">
<li>Category 1</li>
<li>Category 2</li>
<li class="selected">Category 3</li>
<li>Category 4</li>
</ul>
What this produces is all list items with a blue background (from the "nav" class), as if there were no "selected" class. However, when I take out the background color from the "nav" class, I get the red background for the list item with the "selected" class.
I would like to use the "selected" class for other items on the page (i.e. other list items, divs, etc.).
How would I go about solving this?
Thank you in advance.
Live Demo
If you want this to be highlighted depending upon the page your user is on then do this:
Source
The ul.nav li is more restrictive and so takes precedence, try this:
Scenario: I have a navigation menu like this. Note: Link
<a> is child of list item <li>
. I wanted to change the background of the selected list item and remove the background color of unselected list item.I tried to add a class .active into the list item using jQuery but it was not working
Solution: Basically, using .active class changing the background-color of list item does not work. So I changed the css class name from .active to "nav li.active a" so using the same javascript it will add the .active class into the selected list item. Now if the list item
<li>
has .active class then css will change the background color of the child of that list item<a>.
This is an issue of selector specificity. (The selector
.selected
is less specific thanul.nav li
.)To fix, use as much specificity in the overriding rule as in the original:
You might also consider nixing the
ul
, unless there will be other.nav
s. So:That's a bit cleaner, less typing, and fewer bits.
1) You can use the
!important
rule, like this:See http://www.w3.org/TR/CSS2/cascade.html#important-rules for more info.
2) In your example you can also get the red background by using
ul.nav li.selected
instead of just.selected
. This makes the selector more specific.See http://www.w3.org/TR/CSS2/cascade.html#specificity for more info.