I'm trying to give each menu li a unique background color on hover, and I want to do it using css2.
<ul>
<li>
<li>
<li>
<li>
</ul>
I was able to add a background onto the first element, using the following:
nav ul > li:hover:first-child a { background-color:red !important; }
When I add a different background onto the 2ndelement, the hover effect for the next element appears only when I place my cursor over the first element.
This is my code so far:
nav ul > li:hover:first-child a { background-color:red !important; }
nav ul > li:hover:first-child + li a { background-color:blue !important; }
Is there a proper way to do this with CSS2?
I'm tried to get some insight into this Boltclock's answer in the link below.
How do I get the nth child of an element using CSS2 selectors?
Any help would be greatly appreciated.
The nth child is represented by the last element in the +
chain (before the combinator immediately following it, if any), so you would attach the :hover
selector to that element like so:
nav ul > li:hover:first-child a { background-color:red !important; }
nav ul > li:first-child + li:hover a { background-color:blue !important; }
If you wish to make this clearer for the first child, you can reorder the pseudo-classes, placing :hover
at the end (i.e. after :first-child
):
nav ul > li:first-child:hover a { background-color:red !important; }
nav ul > li:first-child + li:hover a { background-color:blue !important; }
Lastly, as others have mentioned, you should remove the !important
s unless you have a specific reason to use them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments