3

我不知道如何将奇/偶: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;}

​</p>

4

2 回答 2

6

在 HTML 中,dtdd是彼此的兄弟,在同一个 parent 下dl。因此,如果您在单个dt和之间交替,那么您的所有元素都将是,而您的所有元素都将是.dddldt:nth-child(odd)dd:nth-child(even)

您可能正在寻找:nth-of-type(),这将帮助您只检查dtordd类型,不像:nth-child()它不关心它是什么类型的元素,只关心它相对于父元素的位置。

如果你想让每一个奇数的dd绿色和每一个偶数dd的红色:

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

更新的小提琴

于 2012-06-29T22:30:57.363 回答
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 }
于 2021-04-12T11:50:16.343 回答