Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select doubles using nth-child() in CSS3

Say I have the following structure for a list:

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

and each <li> is 50% width so I want every two to have the same background colour like this:

<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 using the 'nth-child()' CSS selector so as to minimise code?

like image 456
Dan Avatar asked Mar 28 '12 17:03

Dan


People also ask

How do I select a specific Nth child in CSS?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

What is the nth child () selector used for?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

How do I select all 3 children in CSS?

Yes, you can use what's known as :nth-child selectors. In this case you would use: li:nth-child(3n) { // Styling for every third element here. }


2 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 with the 1st, and 2nd as color #CCC and every 4th element starting with the 3rd and 4th as #DDD

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

like image 112
jzworkman Avatar answered Sep 28 '22 07:09

jzworkman


li{
   /* All LIs*/
}
li:nth-child(4n+1),
li:nth-child(4n+2) {
   /* Li 1, 2,
         5, 6,
         9, 10 */
}
like image 36
YMMD Avatar answered Sep 28 '22 07:09

YMMD