The nth-child selector in CSS
Web Design with HTML & CSS
🕑 This lesson will take about 10 minutes
In a couple of the previous lessons, we looked at child selectors and pseudo classes. In this lesson, we will move on to the nth-child selector. The nth-child selector is used to select child elements belonging to a parent element where n can represent either a number, keyword or formula. For example, you could select the nth child element where n could be 5. Or, you could apply a style to every nth element (eg. every 2nd child) in a div. When using the nth-child selector, ‘n’ can be a number, a keyword or a formula.
In the example below, we can change the colour of the 5th paragraph inside a div with a class called ‘content’. Because ‘n’ is 5, only the 5th element will be selected.
Here is an example of a keyword being used to apply a background-color style to odd paragraphs inside a div with a class called ‘content’:
Watch the video below to see some of the different numbers, keywords, and formulas that can be used with the CSS nth-child selector. Then scroll down to see the sample code.
And here is the HTML & CSS code with a range of different examples demonstrated in the video. Comments have been added to the code explaining what each section of the code is responsible for:
Next lesson: Styling lists