I have a simple menu with two buttons and each button is a dropdown; each display two sub-buttons. I want for each sub item to be a different background color, as you can see from my CSS below.
#nav:first-child > li li:first-child {background: yellow;}
#nav:first-child > li li:nth-child(2) {background: red;}
#nav:nth-child(2) > li li:first-child {background: green;}
#nav:nth-child(2) > li li:nth-child(2) {background: blue;}
So far my CSS only works for the first sub-buttons; sub-button one is yellow, and sub-button two is red. Unfortunately sub-button three is yellow instead of green, and sub-button four is red instead of blue. How can I change my last two lines of code to achieve the desired results?
**keep in mind, the dropdown is a nested LIST. HTML example below:
<div id="nav">
<ul>
<li>link 1
<ul>
<li>SUB link 1</li>
<li>SUB link 2</li>
</ul>
</li>
<li>link 2
<ul>
<li>SUB link 3</li>
<li>SUB link 4</li>
</ul>
</li>
</ul>
</div>
IE7-8 Support
You were using
:nth-childto begin with, which is not supported in those browsers, so I can see why those who answered did not care about support, as it would have appeared that you did not care about such support. However, selectors can be made to work for those. Using the adjacent sibling combinator+with the:first-childin key points creates the same effect as:nth-child(2)See Fiddle.
IE6
You cannot get IE6 support without either javascript or directly putting classes on each of the
lielements, as IE6 does not support:first-childor+. Personally, for color variations, you should just let IE6 go. If you insist, and do not want to use javascript to get selector function through that, then you are resolved to change the html:With this
Of course, that would work on any browser supporting css. But that is also not what I suspect you want to do. So again, leave IE6 to itself and forget about accommodating the color change on that or use javascript (perhaps through Modernizr, Jquery, MooTools, etc.) to do it.