csscss-selectors

Nth Child for ul li a links


I am trying to get a special styling for ul li a elements. Here's the code:

<ul id="menu">
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
</ul>

I'd like the second link (Two) to have a different styling (color) than the other two (One and Three).

This is what I've been trying, but it does not seem to work:

#menu li a:nth-child(even) {color:red;}

Any tips for getting this to work? Here is a fiddle all set up:

http://jsfiddle.net/DSkfH/


Solution

  • :nth-child() selects elements from amongst their siblings, in this case the a elements have no siblings, so you'll need to employ the :nth-child() pseudo-class to the li instead:

    #menu li:nth-child(even) a {color:red;}
    

    JS Fiddle demo.