Home > Article > Web Front-end > How to Apply Alternating Colors to List Items with the 'Parent' Class Using nth-child Selector?
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; }
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!