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/
Thanks!
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
Writing Complex :nth-child() Selectors It works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.
The :nth-child() is a CSS pseudo-class selector that allows you to select elements based on their index (source order) inside their container. You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() .
: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.
Try
#menu li:nth-child(even) a {color:red;}
if you want the color on the li as well you'll need also
#menu li:nth-child(even) {color:red;}
You cant just have the li
selector because the colour property is not inherited by the a
tag.
http://jsfiddle.net/DSkfH/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With