I'm trying to apply odd/even selectors to all elements in a list with the class parent.
HTML:
<ul> <li class="parent">green</li> <li class="parent">red</li> <li>ho ho ho</li> <li class="parent">green</li> <li class="parent">red</li> </ul>
CSS:
.parent:nth-child(odd) { background-color: green; } .parent:nth-child(even) { background-color: red; } ul { width:100px; height: 100px; display: block; }
Link to jsFiddle
But the colors are resetting. I want the list items to be the color of the text.
Is there a way to do this?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With