The real power of the nth-child() selector
(a CSS3 structural pseudo-class) lies in its ability to accept numeric formulas as its arguments, for example 2n+1
. Once we get used to these features, the possibilities are infinite. Let's see some examples.
<ul id="test"> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> </ul>
#test li:nth-child(2n+1) {color: green;} #test li:nth-child(odd) {background: silver;} #test li:nth-child(5) {font-weight: bold; text-transform: uppercase;} #test li:nth-child(7n-6) {border: medium solid; padding: 0.5em;}
The first and second rule select all odd elements, the former with a formula, the latter with a keyword. The third rule selects the fifth list item (remember that the numbering starts from 1, not 0). Finally, the last rule shows what happen when our formula has a negative value. In this case, this rule will match the first list item (seven list items less six equals to one).