In a couple of the previous tutorials, we looked at child selectors and pseudo classes. In this tutorial, 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.
.content p:nth-child(5){ color:red; }
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’:
.content p:nth-child(odd){ background-color:green; }
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.
Here is the HTML sample code:
<html> <head> <title>The nth-child selector</title> <link rel="stylesheet" href="theme.css" type="text/css"/> </head> <body> <div class="content"> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> <p>The quick brown fox jumps over the lazy dog.</p> </div> </body> </html>
And here is the 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:
/* Selects only 5th element */ .content p:nth-child(5){ font-weight: bold; } /* Selects odd elements */ .content p:nth-child(odd){ color: red; } /* Selects every 3rd element */ .content p:nth-child(3n){ text-decoration: underline; } /* Selects all except first 4 elements */ .content p:nth-child(n+5){ font-family: Arial; } /* Selects only first 4 elements */ .content p:nth-child(-n+4){ font-style: italic; } /* Selects every 3rd element starting from the 2nd element */ .content p:nth-child(3n+2){ background-color: yellow; }