Home >Web Front-end >CSS Tutorial >Why Doesn't My CSS :odd and :even Selector Work as Expected?

Why Doesn't My CSS :odd and :even Selector Work as Expected?

DDD
DDDOriginal
2024-12-29 19:22:16847browse

Why Doesn't My CSS :odd and :even Selector Work as Expected?

Styling Even and Odd Elements

The CSS pseudo-classes :odd and :even allow you to apply styles to odd and even instances of elements in a list. However, an issue arises when using these pseudo-classes in conjunction with a base styling rule, leading to unexpected results.

For example, consider the following CSS and HTML code:

li { color: blue }
li:odd { color:green }
li:even { color:red }
<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
</ul>

You might expect this to produce a list of alternating colors, but instead, all list items are blue.

Solution

To solve this, you can use the nth-child pseudo-class instead of :odd and :even. The syntax for nth-child is as follows:

li:nth-child(n) {...}

where n represents the position of the element within its parent.

To style odd and even list items, you can use the following CSS:

li {
    color: black;
}
li:nth-child(odd) {
    color: #777;
}
li:nth-child(even) {
    color: blue;
}
<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
</ul>

This will result in a list of black list items, with every other item alternating between gray (#777) and blue.

The above is the detailed content of Why Doesn't My CSS :odd and :even Selector Work as Expected?. 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