:具有定义列表的nth-child()奇数/偶数伪类

时间:2012-06-29 22:28:30

标签: html css css3 css-selectors pseudo-class

我无法弄清楚如何将奇数/偶数:nth-child()伪类应用于定义列表

<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/

使用正确的:nth-​​of-type伪类。

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;}

2 个答案:

答案 0 :(得分:6)

在HTML中,dtdd都是同一个父dl下的兄弟姐妹。因此,如果您在单个dt中的dddl之间进行切换,则所有dt元素将:nth-child(odd) dd 1}}元素将为: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

答案 1 :(得分:0)

请注意,从 HTML 5.2 开始,允许将“div 作为 dl 元素的子元素”。

就像这样:

<dl>
  <div>
    <dt>Name</dt>
    <dd>Godzilla</dd>
  </div>
</dl>

你的 css 可能是这样的:

dl { background-color: blue; padding: 10px }
div:nth-child(odd) { background-color:green }
div:nth-child(even) { background-color:red }
相关问题