The :nth-child(n) selector is used to select elements based on their position within a parent element's list of children. The n can be a number, a keyword, or a formula, and it determines which elements are selected based on their ordinal position.
selector:nth-child(n) {
/* CSS Property */
}
The n in the parentheses can be a number, a keyword (such as odd or even), or a functional notation (such as An+B).
p:nth-child(odd) {
background-color: lightblue;
}
p:nth-child(even) {
background-color: lightgreen;
}
• A is an integer that represents the step size.
• n is a counter starting from 0.
• B is an integer that represents the offset.
li:nth-child(3n+1) {
color: red;
}
This will select the 1st, 4th, 7th, etc., elements.
li:nth-child(2n) {
color: blue;
}
This will select the 2nd, 4th, 6th, etc., elements.
li:nth-child(5) {
font-weight: bold;
}
This will select only the 5th element.
<!DOCTYPE html>
<html>
<head>
<style>
li:nth-child(odd) {
background-color: lightgray;
}
li:nth-child(even) {
background-color: white;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(3n) {
background-color: yellow;
}
</style>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
</body>
</html>
Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
Paragraph 5
Paragraph 6
Paragraph 7
Paragraph 8
Paragraph 9