CSS Tips & Tricks Using Nth-Child
We’ll detail some design examples where there is a list of elements that have colour changes within one or more of the list items.
Written by: Tom Buxton
16/06/2022
3 min read
As a developer it’s exciting to come across designs where I can see a clear use for :nth-child or :nth-of-type.
There’s almost always a use for nth-child in a design, usually when a colour or layout needs to change inside a list of items.
Below are design examples where there is a list of elements that have colour changes within one or more of the list items.
Although the 2 nth selectors (:nth-child and :nth-of-type) are very similar, they can have two completely different uses:
For example, we have 3 paragraphs inside a section
The 2 following CSS rules will achieve the same objective, giving the third paragraph a colour of blue.
However, there is a difference in these 2 selectors. The p:nth-child(3) CSS selector rule we created above selects the elements based of the following rules:
-
It’s a paragraph (p:)
-
It is the third child (3)
The p:nth-of-type(3) CSS selector rule works slightly different and selects the elements based of 1 simple
rule:
-
Select the third paragraph child of a parent.
Confused yet? Don’t worry I will clear things up and you will see the difference…
Now we will add a heading to our section.
With the addition of the heading, the 2 CSS rules we created won’t work the same as they did initially.
The following, nth-child CSS rule will now select paragraph 2 instead of paragraph 3. It’s working as expected (1. It’s a paragraph and 2. It’s the third child) but, it can confuse developers because its not working as they expected.
And the following, nth-of-type CSS rule will still work exactly the same as before, selecting the third paragraph and giving it a colour of blue.
Hopefully that clears things up and you can see how these 2 CSS selectors work and how they have their differences. Below are some code pens for you to see the 2 examples we just worked through.
CSS simple nth-child recipes While we are on the topic I figured I would leave some simple nth-child recipes for you to enjoy and mostly for me to come back to, and copy & paste.