Home >Web Front-end >CSS Tutorial >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; }
Explanation:
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!