Episode 23 of 53
Nth of Type Selector
Learn :nth-of-type() to select elements based on position among siblings of the same type.
The :nth-of-type() pseudo-class works like :nth-child(), but only counts elements of the same type.
nth-child vs nth-of-type
<div>
<h2>Title</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</div>
/* Selects the 2nd child overall (first <p>) */
p:nth-child(2) { color: red; }
/* Selects the 2nd <p> element (Paragraph 2) */
p:nth-of-type(2) { color: blue; }
Practical Examples
/* Style every other paragraph */
p:nth-of-type(even) {
background: #f0f4f8;
padding: 1rem;
border-radius: 4px;
}
/* Style the first 2 images in a gallery */
.gallery img:nth-of-type(-n+2) {
width: 50%;
border: 3px solid gold;
}
Combining with Other Selectors
/* Every 3rd paragraph inside articles */
article p:nth-of-type(3n) {
font-style: italic;
border-left: 3px solid #3498db;
padding-left: 1rem;
}
When to Use Which
- Use
:nth-child()when you care about position among all siblings - Use
:nth-of-type()when you care about position among siblings of the same element type