Home > Article > Web Front-end > How to Alternate Background Colors for ".parent" List Items With Intervening Non-".parent" Elements?
Using :nth-child(even/odd) Selector with Class:
You want to apply alternating background colors to list items with the ".parent" class. However, the colors currently reset.
Problem:
The ".parent" elements are not behaving as expected due to the presence of non-".parent" elements within the list.
Solution:
Normally, the desired behavior cannot be achieved using only the :nth-child selector. However, you can employ the general sibling combinator (~):
CSS Code:
.parent:nth-child(odd) { background-color: green; } .parent:nth-child(even) { background-color: red; } /* After the first non-.parent, toggle colors */ li:not(.parent) ~ .parent:nth-child(odd) { background-color: red; } li:not(.parent) ~ .parent:nth-child(even) { background-color: green; } /* After the second non-.parent, toggle again */ 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; }
This approach alternates the colors for limited numbers of "excluded" non-".parent" elements, achieving the desired alternating pattern.
The above is the detailed content of How to Alternate Background Colors for ".parent" List Items With Intervening Non-".parent" Elements?. For more information, please follow other related articles on the PHP Chinese website!