7

Is it possible to select every other group of three in CSS? And if it is; how?

So in the sample below apply style to the 4-6 and 10-12 lis.

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
     <li>4</li>
     <li>5</li>
     <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
     <li>10</li>
     <li>11</li>
     <li>12</li>
</ul>

I know [pure] JavaScript and jQuery can do this but I am looking for a pure CSS solution if it exists.

2

2 Answers 2

12

You're looking for nth-child:

ul li:nth-child(6n+4),ul li:nth-child(6n+5),ul li:nth-child(6n+6) {
    background:red;
}

http://jsfiddle.net/bhlaird/utEP4/1/

3
  • 2
    deja vu: stackoverflow.com/questions/18970189/… :) Oct 1, 2013 at 23:16
  • +1 I fiddled around with the nth-child before I posted the question. I figured some smart SOer would get it. I actually wanted every other 7 (for calendar rows) but figured every other 3 would be easier to replicate - jsfiddle.net/utEP4/8. Thanks! Oct 2, 2013 at 3:18
  • @BYossarian If that question was better asked I would have found it. Oct 2, 2013 at 3:23
1

You could achieve this with a single selector, using a combination of :not and :nth-child.

ul > li:not(:nth-child(6n+1)):not(:nth-child(6n+2)):not(:nth-child(6n+3))  {
    color:blue;
}

jsFiddle here

Using that selector by itself is pretty useless, though, considering you cannot style the other elements.

ul > li:not(:nth-child(6n+4)):not(:nth-child(6n+5)):not(:nth-child(6n+6))  {
    color:red;
}

Using a combination of both will allow you to style everything, see the demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.