Select doubling using nth-child () in CSS3

Let's say I have the following structure for a list:

<ul>
    <li></li><li></li>
    <li></li><li></li>
</ul>

and each <li>is 50% of the width, so I want each of the two to have the same background color as follows:

<ul>
    <li style="background:#CCC;"></li><li style="background:#CCC;"></li>
    <li style="background:#DDD;"></li><li style="background:#DDD;"></li>
    <li style="background:#CCC;"></li><li style="background:#CCC;"></li>
    <li style="background:#DDD;"></li><li style="background:#DDD;"></li>
</ul>

Can I do this with the nth-child () CSS selector to minimize code ?

+5
source share
5 answers
ul li:nth-child(4n+1),
ul li:nth-child(4n+2) {
  background: #CCC;
}
ul li:nth-child(4n+3),
ul li:nth-child(4n+4) {
  background: #DDD;
}

This will give you every 4th element starting from the 1st and 2nd colors of #CCC and every 4th element starting from the 3rd and 4th as #DDD

jsfiddle here: http://jsfiddle.net/mU2tn/1/

+5
source
li{
   /* All LIs*/
}
li:nth-child(4n+1),
li:nth-child(4n+2) {
   /* Li 1, 2,
         5, 6,
         9, 10 */
}
+2
source

, CSS (3). jsFiddle.

li {
    width:100%;
}
li:nth-child(4n) {
    background:#999;
}
li:nth-child(4n-1) {
    background:#999;
}
li:nth-child(4n-2) {
    background:#ccc;
}
li:nth-child(4n-3) {
    background:#ccc;
}

+2

, CSS , .

ul li:nth-child(4n+1), ul li:nth-child(4n+2) {
    background: #ccc;
}

ul li:nth-child(4n+3), ul li:nth-child(4n){
    background: #ddd;
}

This JSFiddle shows this in action. http://jsfiddle.net/u2W84/

+2
source

Perhaps all the other answers work, but this is what I would do:

ul li {
    background: red;
}

ul li:nth-child(odd), 
ul li:nth-child(odd) + li {
    background: green;
}

Edit: no, sorry this didn't work: P Gimme a sec.

+1
source

All Articles