htmlcsscss-selectors

How can I style even and odd elements?


Is it possible to use CSS pseudo-classes to select even and odd instances of list items?

I'd expect the following to produce a list of alternating colors, but instead I get a list of blue items:

li { color: blue }
li:odd { color:green }
li:even { color:red }
<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
  </ul>


Solution

  • Demo: http://jsfiddle.net/thirtydot/K3TuN/1323/

    li {
        color: black;
    }
    li:nth-child(odd) {
        color: #777;
    }
    li:nth-child(even) {
        color: blue;
    }
    <ul>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
        <li>ho</li>
    </ul>

    Documentation: