How many times have you seen a piece of JavaScript or PHP code that’s only purpose is to add a specific class to the first, alternate or last element of a list or row of table? With CSS3 you can easily get rid of all of that logic and replace it clean and simple CSS selectors. This will help tidy up your code and depending on what exactly the code is doing reduce CPU load by removing unnecessary recursions (This is of course a minimal gain, but every little bit counts)
What is the nth-child
The nth-child is a pseudo-class selector that can be applied to any element, all you need to do is specify what you want the ‘n’ to be.
ol.nth li:nth-child(n) {
background-color: #cccccc;
}
Numeric values
The ‘n’ can be something simple like ‘1’ or ‘5’, specifying a numerical value simple states you want match the element at that position or index
ol.nth-num li:nth-child(1), ol.nth-num li:nth-child(5) {
background-color: #cccccc;
}
Alternating elements
There 2 keywords that are available to you to use, they are unsurprisingly ‘odd’ and ‘even’. I’m not sure why they didn’t include the ‘first’ and ‘last’ keywords from the ‘:last-child’ and ‘:first-child’ pseudo selectors, which I think is a bit of an over-site.
ol.nth-alt li:nth-child(odd) {
background-color: #cccccc;
}
ol.nth-alt li:nth-child(even) {
background-color: #c5c5c5;
}
Formula based values
What happens if you want to only have every 4th element different? That’s where the formula based values come in. The formula layout is as follows ‘xn+y’, where x is the step or how many elements you want to count per iteration and y is the offset from the index start (or how many you want to skip)
The equivalent pseudo JavaScript, PHP or C# code would be something like this
for(i = y; i < length; i+x){
//do something
}
Here we’re starting from the 1st element (index of 0)
ol.nth-for1 li:nth-child(3n+0) {
background-color: #cccccc;
}
Here we’ll skip to the 5th item and start counting from there (index of 5)
ol.nth-for2 li:nth-child(3n+5) {
background-color: #cccccc;
}
Other nth-* Selectors
Several other nth-* selectors are available, they’re all used in the same way but are for different uses
Have a play around with them and see what you can come up with