Home > Web Front-end > CSS Tutorial > Why are My Alternating Colors Resetting When Using :nth-child(even/odd) with a Class?

Why are My Alternating Colors Resetting When Using :nth-child(even/odd) with a Class?

Susan Sarandon
Release: 2024-11-08 07:13:02
Original
1063 people have browsed it

Why are My Alternating Colors Resetting When Using :nth-child(even/odd) with a Class?

:nth-child(even/odd) Selector with Class Issue

You aim to apply alternating colors to list items with the "parent" class. However, you encounter problems with the colors resetting. To resolve this, consider the following:

Solution:

Since CSS rules are applied top-to-bottom, the :nth-child(even/odd) selectors will potentially override previous color settings. To address this, use the general sibling combinator (~) to toggle colors after non-"parent" elements:

.parent:nth-child(odd) {
    background-color: green;
}
.parent:nth-child(even) {
    background-color: red;
}

/* Alternate colors after non-.parent elements */
li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: red;
}
li:not(.parent) ~ .parent:nth-child(even) {
    background-color: green;
}
Copy after login

Explanation:

  • The first two rules set the alternating colors for "parent" elements.
  • Subsequent rules use the ~ combinator to toggle colors after non-"parent" elements.
  • Each set of rules alternates the colors with increased specificity, ensuring the desired behavior.

Limitations:

While this method allows you to achieve alternating colors for a limited number of non-"parent" elements, there is a limit to how far you can extend this approach.

The above is the detailed content of Why are My Alternating Colors Resetting When Using :nth-child(even/odd) with a Class?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template