5

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!

4

2 回答 2

14

:nth-child()从它们的兄弟元素中选择元素,在这种情况下,a元素没有兄弟元素,因此您需要使用:nth-child()伪类来li代替:

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

JS 小提琴演示

于 2013-07-29T18:29:35.060 回答
4

尝试

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

如果你也想要 li 上的颜色,你还需要

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

您不能只拥有li选择器,因为a标签不继承颜色属性。

http://jsfiddle.net/DSkfH/3/

于 2013-07-29T18:29:08.980 回答