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.
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!