Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

Thanks!

like image 657
HelloWorld Avatar asked Jul 29 '13 18:07

HelloWorld


People also ask

How do you select the nth child?

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.

What is the nth child () selector used for?

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.

How do I select nth child in SCSS?

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.

What is an nth child?

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() .


2 Answers

: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.

like image 119
David Thomas Avatar answered Oct 15 '22 17:10

David Thomas


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/

like image 23
Musa Avatar answered Oct 15 '22 19:10

Musa