The :nth-of-type()
pseudo-class is similar to :nth-child()
, but it only considers elements of a specific type. This is incredibly useful when you have a mix of different elements within a parent and want to target a specific type.
Example 1: Styling Every Other Paragraph
/* Targets every other <p> element */
p:nth-of-type(2n) {
color: #777;
}
Explanation
This code will change the text color of every second paragraph (<p>
) inside a container, even if there are other elements like headings or images between them.
Example 2: Highlighting a Specific Heading
/* Targets the second <h2> element */
h2:nth-of-type(2) {
border-bottom: 2px solid #333;
}
Explanation
This CSS selects the second <h2>
element within its parent and adds a solid bottom border, regardless of other elements' positions.
Example 3: Styling in Groups of a Specific Type
/* Styles every fourth image in a gallery */
img:nth-of-type(4n) {
border: 2px solid #dc3545;
}
Explanation
This rule applies a red border to every fourth image (<img>
) in a container, ignoring any other element types.
Example 4: Selecting the First Few of a Type
/* Targets the first two blockquotes */
blockquote:nth-of-type(-n+2) {
font-style: italic;
}
Explanation
This CSS makes the text of the first two <blockquote>
elements italic. It only counts blockquotes and ignores other elements.
Example 5: Skipping the First Few of a Type
/* Targets all spans after the first three */
span:nth-of-type(n+4) {
color: #28a745;
}
Explanation
This code changes the text color to green for all <span>
elements starting from the fourth one within their parent.