"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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()`?

Published on 2024-12-26
Browse:517

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 }

Use:

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3