:nth-child(even/odd) selector with class [duplicate]

In general what you want is not possible, but there is a way to achieve the desired behavior for limited numbers of “excluded” elements: the general sibling combinator ~.

The idea is that for each occurrence of a non-.parent element subsequent .parent elements will have their colors toggled:

.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;
}

See it in action.

Of course there is a limit to how far one would be willing to take this, but it’s as close as you can get with pure CSS.

Leave a Comment