Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to select every other group of three in CSS?

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.

like image 514
iambriansreed Avatar asked Oct 01 '13 23:10

iambriansreed


People also ask

How do I select all 3 elements in CSS?

How do I target every third element in CSS? formula (an + b) In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.

How can you select a group of different elements in CSS?

To group selectors, separate each selector with a comma.

Can I select multiple elements at once with CSS?

It is possible to give several items on your page the same style even when they don't have the same class name. To do this you simply list all of the elements you want to style and put a comma between each one.

Can a CSS rule have multiple selectors?

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator. There are four different combinators in CSS: descendant selector (space)


2 Answers

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/

like image 56
Barbara Laird Avatar answered Sep 28 '22 03:09

Barbara Laird


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.

like image 20
Josh Crozier Avatar answered Sep 28 '22 03:09

Josh Crozier