Search code examples
htmlcsscss-selectorspseudo-class

:nth-child() odd/even pseudo classes with definition list


I can't figure out how to apply the odd/even :nth-child() pseudo classes to definition lists

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

new fiddle:

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

with the correct :nth-of-type pseudo class.

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


Solution

  • In HTML, both dt and dd are siblings of one another, under the same parent dl. As such, if you're alternating between dt and dd in a single dl, then all your dt elements will be :nth-child(odd) while all your dd elements will be :nth-child(even).

    You're probably looking for :nth-of-type() instead, which will help you check only either the dt or dd type, unlike :nth-child() which doesn't care what kind of element it is, only its position relative to the parent.

    If you want to make every odd dd green and every even dd red:

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

    Updated fiddle