Ever want to select only the first element in a list? What about the last element? Or how about odd or even element? What about every 3rd element? Or, what about selecting the first 3 elements or the last 3 elements?
Of course you do, and if you haven’t wanted to do this in the past you will want to do in the future at some point, probably sooner than you think.
You can approach the problem with classes, by adding a special class to say the first three elements or every other element. But this becomes very tedious and lacks flexibility. A better solution would be a CSS selector. Well here it is :nth-child(). The :nth-child() selector allows you to accomplish the following.
Imagine for these examples that you have a page with 9 divs, each with the class name box. To select all of these you’d use: .box I’ll modify this selection with :nth-child() in the examples below to illustrate how it works.
- Pick any single element – .box:nth-child(3) /* Selects the 3rd element */
- Pick out only the odd elements – .box:nth-child(odd) /* Selects all odd numbered elements */
- Pick out only the even numbered elements – .box:nth-child(even) /* Select all even numbered elements */
These first three examples use :nth-child() in it’s most basic an obvious form. Include the integer position of the element or a key word, odd or even.
Here’s a few more examples.
- Pick every 3rd element for example 3, 6, 9 etc. – .box:nth-child(3n)
- Pick every 5th element for example 5, 10, 15 etc. – .box:nth-child(5n)
Here you can think of n as an integer 1, 2, 3 etc. multiplied by the number on the left. So 3n would be 3, 6, 9 etc. There’s more, how these examples.
- Pick every third element starting with the first. For example boxes 1, 4, 7, 10 etc. – .box:nth-child(3n+1)
- Pick every third element starting on 5, for example: 5, 8, 11, etc. – .box:nth-child(3n+5)
- Pick every element after the 4th: 5, 6, 7, 8 etc. – .box:nth-child(n+5)
You can think of the last example: .box:nth-child(n+5) as .box:nth-child(1n+5). Which might make more sense.
Here we’re using an+b. Where elements are selected as a*n+b. Which works out as the following for 3n+5
- (3*1)+1 = 4
- (3*2)+1 = 7
- (3*3)+1 = 10
The last example above .box:nth-child(n+5) would select all of the elements after the first 4. To select only the first 4 elements you can use :nth-child() in this way:
- Pick the first 4 elements, for example: 1, 2, 3 and 4. – .box:nth-child(-n+4)
Think of this as:
- (-1*0) + 4 = 4
- (-1*1) + 4 = 3
- (-1*2) + 4 = 2
- (-1*3) + 4 = 1
An alternative to :nth-child() is :nth-last-child(). Which works in the same way, but starts counting backwards from the last element.
What could you use this for? Here are a few ideas:
- Selecting every other item in a list.
- Selecting the first item in a list.
- Selecting the first three items in a list.
- Setting the margins on the last item in every row.
- Selecting the first row of elements.
- Selecting the last row of elements.