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
Release: 2025-01-03 09:00:39
Original
518 people have browsed it

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 }
Copy after login

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;
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template