Home > Web Front-end > CSS Tutorial > Even vs. Odd List Item Styling in CSS: `li:odd`/`:even` or `:nth-child()`?

Even vs. Odd List Item Styling in CSS: `li:odd`/`:even` or `:nth-child()`?

DDD
Release: 2024-12-21 03:58:10
Original
757 people have browsed it

Even vs. Odd List Item Styling in CSS:  `li:odd`/`:even` or `:nth-child()`?

Styling Even and Odd List Elements: Pseudo-Classes vs. nth-child

When trying to achieve alternating colors for list items using CSS pseudo-classes, you may encounter issues. While it might seem logical to use li:odd and li:even for this purpose, the behavior can be unpredictable.

To effectively style even and odd instances of list items, consider using the following approach:

Instead of:

li { color: blue }
li:odd { color:green }
li:even { color:red }
Copy after login

Use:

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

By replacing :odd and :even with :nth-child(odd) and :nth-child(even), the desired alternating coloring effect is achieved. This is because :nth-child allows you to select elements based on their position within the list, ensuring that the correct styling is applied to each item.

The above is the detailed content of Even vs. Odd List Item Styling in CSS: `li:odd`/`:even` or `:nth-child()`?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template