I'm not going to lie, using nth-child has always made my brain hurt when using it in CSS. Maybe it's the fact that math is involved and for the most part, I can avoid math in most other areas of CSS except this. I'm certainly not the first person to take a crack at explaining it but I thought I'd give it a try.
View the Nth-Child Visual Calculator »
Simply Algebra
Using nth-anything in CSS takes many of us back to our 9th grade Algebra class. The reason for this is the formula used for nth-child uses "variables". These are represented as n. The example below is an example:
ol li:nth-child(2n+1)
{
...
}
Nth-Child Iteration Table
Below is a table illustrating how our formula above works. It will loop until there are no more elements to loop through using the base selector ol li
N | Nth-Selector | Math Formula | Result |
---|---|---|---|
0 | 2n+1 | 2 * 0 + 1 | 1 (first element) |
1 | 2n+1 | 2 * 1 + 1 | 3 (third element) |
2 | 2n+1 | 2 * 2 + 1 | 5 (fifth element) |
3 | 2n+1 | 2 * 3 + 1 | 7 (seventh element) |
4 | 2n+1 | 2 * 4 + 1 | 9 (ninth element) |
The selector ol li:nth-child(2n+1) will therefore select every odd element in the ordered list.
Keywords
CSS also has some keyword values that can be used for nth-child to make writing the formulas easier for common nth-child selectors:
ol li:nth-child(even)
{
...
}
ol li:nth-child(odd)
{
...
}
Common Nth-Child Selectors
A quick shortcut to remember if you want to select every "x" element is to take the number you're looking for and multiply it times n.
Child | Selector |
---|---|
Every Second Element | ol li:nth-child(2n) |
Every Third Element | ol li:nth-child(3n) |
Every Fourth Element | ol li:nth-child(4n) |
Every Fifth Element | ol li:nth-child(5n) |
Other Nth-Child Selectors
Nth-Child also accepts negative numbers and subtraction as well as single numbers to select a specific element by its index.
Child | Selector |
---|---|
Only the First Element | ol li:nth-child(1) |
Only the Third Element | ol li:nth-child(3) |
Only the First Three Elements | ol li:nth-child(-n+3) |
Still Confused?
Check out the handy nth-child visual calculator I created and enter in some of the examples I've provided in my article. It will visually run and select the elements from your selector.