Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

enter image description here

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?

like image 933
nilsi Avatar asked Jul 03 '13 21:07

nilsi


1 Answers

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.

like image 114
Jon Avatar answered Oct 23 '22 09:10

Jon