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?
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.
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.
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. }
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/
li{
/* All LIs*/
}
li:nth-child(4n+1),
li:nth-child(4n+2) {
/* Li 1, 2,
5, 6,
9, 10 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With