: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.
This is a common misperception
The :nth-child
and :nth-of-type
selectors do not look at "class" or anything else for counting. They only look at either (1) all elements, or (2) all elements of a certain "type" (not class, not an attribute, nothing but the type of element--div
or li
etc.).
So you cannot skip it with pure CSS without either knowing your exact html structure (and then, only if there are in fact a few elements you are dealing with--see Jon's answer for one such way, where you need to know how many non-parent elements you are dealing with, and as you can see and he notes the practical limits are very small), or by using javascript.