How to Use nth-of-type in CSS: Syntax and Examples
Use the
:nth-of-type(n) CSS pseudo-class to select elements of a specific type based on their position among sibling elements. Replace n with a number, formula, or keyword to target the desired elements. This selector helps style elements like every 2nd paragraph or the 3rd list item easily.Syntax
The :nth-of-type(n) selector matches elements of the same type based on their order among sibling elements. Here, n can be:
- A number (e.g.,
3) to select the 3rd element of that type. - A formula like
2nto select every 2nd element. - Keywords like
oddorevento select odd or even elements.
css
element:nth-of-type(n) { /* styles here */ }
Example
This example colors every 2nd paragraph blue and the 3rd paragraph red. It shows how :nth-of-type targets elements by their type and position.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>nth-of-type Example</title> <style> p:nth-of-type(2n) { color: blue; } p:nth-of-type(3) { color: red; } </style> </head> <body> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> <p>Paragraph 5</p> </body> </html>
Output
Paragraph 1 (black), Paragraph 2 (blue), Paragraph 3 (red), Paragraph 4 (blue), Paragraph 5 (black)
Common Pitfalls
1. Confusing :nth-of-type with :nth-child: :nth-of-type counts only elements of the same type, while :nth-child counts all element types.
2. Using n without parentheses: Always use parentheses around the argument, like :nth-of-type(2n).
3. Counting resets for different element types: The count restarts for each element type among siblings.
css
/* Wrong: counts all children, not just paragraphs */ div:nth-child(2) { color: red; } /* Correct: counts only paragraphs */ div p:nth-of-type(2) { color: red; }
Quick Reference
:nth-of-type(1)— selects the first element of its type.:nth-of-type(odd)— selects all odd elements of that type.:nth-of-type(even)— selects all even elements of that type.:nth-of-type(3n+1)— selects every 3rd element starting from the first.
Key Takeaways
Use
:nth-of-type(n) to select elements by their type and position among siblings.Remember
:nth-of-type counts only elements of the same type, unlike :nth-child.You can use numbers, formulas, or keywords like
odd and even inside the parentheses.Always include parentheses around the argument in
:nth-of-type().This selector helps style repeated elements easily without adding extra classes.