Home >Web Front-end >CSS Tutorial >Can CSS Pseudo-classes Style Even and Odd List Items?
Styling Even and Odd Elements Using CSS Pseudo-Classes
Question:
Can CSS pseudo-classes be utilized to select and style even and odd elements within a list? A list with alternating colors is the intended outcome, but a list with only blue items is being generated.
Example:
The following code is expected to produce a list with alternating green and red colored items, but instead, all items are blue.
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>
Answer:
To style even and odd elements correctly, the :nth-child pseudo-class should be used instead of :odd and :even:
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>
Demo: [JSfiddle](http://jsfiddle.net/thirtydot/K3TuN/1323/)
The above is the detailed content of Can CSS Pseudo-classes Style Even and Odd List Items?. For more information, please follow other related articles on the PHP Chinese website!