There are many times when we need to select a specific item or set of items from a list. We could achieve this by using JavaScript but there is a simpler way using these CSS pseudo-classes.

Both pseudo selectors allow you to match elements based on their position within a parent element’s list of child elements. They accept an argument that can be a number, the keywords “even” or “odd” or a formula (an+b), and they iterate through all the children of the parent and select the matching elements. 

Here we can see some examples of each one:



In these examples both selectors are doing the same because all the children are the same kind of elements (li tags). In this other example, we can see the difference between them:

The difference is that :nth-child can select any sibling element in an arrangement, not only elements that are specified before the colon, while :nth-of-type targets a particular type of element in an arrangement with relation to similar siblings, not all siblings.

Here are some recipes for nth:child so you can see how it works and what you can do. And with this tool you can test your own recipes for both :nth-child and :nth-of-type.

Author bio

Clara Rodríguez
Clara Rodriguez
UX Developer
I develop the visual part of the website, everything that the user sees and interacts with, trying to recreate the coolest designs by my colleagues. In my free time I like to watch TV shows and hang out with my friends, but if it’s summer you will find me at the beach.


comments powered by Disqus

Related Articles

Sign up to our ClearThought newsletter

Get inspired and learn something new by subscribing to our FREE newsletter. It’s full of ClearPeople's thought-leadership whitepapers, blogs, events, and much more. We promise to not use your email for spam.

Closing this message and/or accessing our website tells us you are happy to receive all cookies on the ClearPeople website.
However, if you would like to, you can change your cookies settings at any time.