:first-of-type in css

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

Suppose we have an article with a title and several paragraphs:

A Title

Paragraph 1.

Paragraph 2.

Paragraph 3.

We want to make the first paragraph larger, as a sort of “lede” or introductory paragraph. Instead of giving it a class, we can use :first-of-type to select it:

p:first-of-type {
font-size: 1.25em;
}

Using :first-of-type is very similar to :nth-child but with one critical difference: it is less specific. In the example above, if we had used p:nth-child(1), nothing would happen because the paragraph is not the first child of its parent (the

). This reveals the power of :first-of-type: it targets a particular type of element in a particular arrangement with relation to similar siblings, not all siblings.
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *