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
Release: 2024-12-29 19:22:16
Original
870 people have browsed it

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 }
Copy after login
<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
</ul>
Copy after login
Copy after login

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

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;
}
Copy after login
<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
    <li>ho</li>
</ul>
Copy after login
Copy after login

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!

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