How to Apply Alternating Colors to List Items with the 'Parent' Class Using nth-child Selector?

Linda Hamilton
Release: 2024-11-09 04:21:02
Original
972 people have browsed it

How to Apply Alternating Colors to List Items with the

Nth-Child Selector with Class: Overcoming Resetting Colors

In an attempt to apply alternating colors to list items with the "parent" class, you might have encountered the issue of colors resetting after certain non-matching elements. This issue arises due to the limitations of the :nth-child selector.

However, a workaround exists using the general sibling combinator (~). By defining rules for elements following non-matching ones, you can toggle the colors for subsequent matching elements. Here's how:

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

/* Toggle colors after first non-parent element */
li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: red;
}
li:not(.parent) ~ .parent:nth-child(even) {
    background-color: green;
}

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

With this approach, each :not(.parent) element serves as a "reset" point, toggling the colors of последующие соответствующие элементы. Although it has limitations in terms of how far it can extend, it's the closest approximation to alternating colors using pure CSS.

The above is the detailed content of How to Apply Alternating Colors to List Items with the 'Parent' Class Using nth-child Selector?. 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