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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-03 09:00:39504browse

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

Styling Even and Odd Elements using CSS Pseudo-Classes

Can CSS pseudo-classes be utilized to differentiate the styling of even and odd list items?

The Expected Outcome:

A list with alternating colors, as seen in the following code snippet:

li { color: blue }
li:odd { color:green }
li:even { color:red }

The Actual Result:

Instead of alternating colors, all list items end up being blue.

The Solution:

To successfully style even and odd elements, it's recommended to use the nth-child pseudo-class, as demonstrated below:

li {
    color: black;
}
li:nth-child(odd) {
    color: #777;
}
li:nth-child(even) {
    color: blue;
}

This solution addresses the alternating color requirement effectively, as showcased in the following code snippet:

<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
</ul>

The above is the detailed content of Can CSS Pseudo-classes Properly 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