What is nth-child and What Does it Mean?
Basically the nth-child is a CSS selector that targets specifically the item you need. We use div ID’s to select the div you wish to style but what happens when we have used it multiple times and want to change one of them? That is where the nth-child comes into play.
How Do I Use The nth-child?
To use the nth-child all you have to do is apply it at the end of a selector in your CSS, the same way you would apply “:hover” or “:focus” etc. Place “:nth-child” then in brackets the number of the one you are targeting.
Notice how the HTML has three div’s, each with the ID of “box”, yet the output shows the colour of each to be different? That is because the nth-child rule is saying the first div with an ID of box has a background colour of #000 (black). The second div with an ID of box has a background colour of #666 (dark gray) and the third div with an ID of box has a background colour of #CCC (light gray).
Pretty Useful, Right?
But it doesn’t stop there. Nth-child goes even further than just selecting the number down of the item. Another example of what the nth-child can do is target every other item. You do this by changing the number inside the brackets to odd or even as shown below:
One Before Last
All Apart From The First Two
As you can see the nth-child can in handy to help us deal with a lot of problems, most commonly styling a menu bar where we want different colour backgrounds for each item. Or styling a table that is frequently being updated. Regardless of your reason, I am sure you will find the nth-child as useful as I do.