Home >Web Front-end >CSS Tutorial >Can CSS Pseudo-classes Style Even and Odd List Items?

Can CSS Pseudo-classes Style Even and Odd List Items?

DDD
DDDOriginal
2024-12-23 11:35:33448browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn