2012-06-29 62 views
3

我无法弄清楚如何将奇/偶:nth-child()伪类适用于自定义列表:第n个孩子()奇/偶伪类与定义列表

<dl> 
    <dt>green foo</dt> 
    <dd>green bar</dd> 
    <dt>red foo</dt> 
    <dd>red bar</dd> 
    <dt>green foo</dt> 
    <dd>green bar</dd> 
</dl> 

<style> 
dl { color: blue } 
dd:nth-child(odd) { color:green } 
dd:nth-child(even) { color:red }​ 
</style> 

http://jsfiddle.net/8Ge5h/2/

新小提琴:

http://jsfiddle.net/8Ge5h/7/

用正确的:第n-的方式伪类。

dd:nth-of-type(even) {color: red;} 
dt:nth-of-type(even) {color: red;} 
dd:nth-of-type(odd) {color: green;} 
dt:nth-of-type(odd) {color: green;} 

+0

什么是不工作?你所有的“dd”都是偶数,所以它们都是红色的...... – sczizzo

+0

你想在这些项目之间“有所不同”是什么? – BoltClock

+0

不同的颜色/背景。为什么他们都是?我希望每隔一天dd改变 – helgatheviking

回答

6

在HTML中,既dtdd是彼此的兄弟姐妹,同一父dl下。因此,如果您在单一dl之间交替使用dtdd,那么您所有的dt元素将为:nth-child(odd),而您的所有dd元素将为:nth-child(even)

你可能寻找替代:nth-of-type(),这将帮助你检查仅采用了dtdd类型,不像:nth-child()不关心它是什么样的元素,其相对于父唯一位置。

如果你想使每个奇数dd绿色和每个偶数dd红:

dd:nth-of-type(odd) { color:green } 
dd:nth-of-type(even) { color:red }​ 

Updated fiddle

+0

:nth-​​type!而已。谢谢! – helgatheviking