Grow your CSS skills. Land your dream job.

:first-of-type

Last updated on:

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:

<article>
  <h1>A Title</h1>
  <p>Paragraph 1.</p>
  <p>Paragraph 2.</p>
  <p>Paragraph 3.</p>
</article>

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 <article>). 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.

The more complete example below demonstrates the use of :first-of-type and a related pseudo-class selector, :last-of-type.

Check out this Pen!

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Works 3.2+ Works 9.5+ 9+ Works Works

:first-of-type was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is impeccable, and the new pseudo-selectors are widely used in production environments. If you require older browser support, either polyfill for IE, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.

Comments

  1. Carla

    Thank you for this article. I just learned about pseudo classes via Greg Rickaby’s drop cap tutorial. I used to manually add span tags to the first letter of each post, but I wanted an easy way to do this that would save me the hassle of having to do that. So I simply added some first-of-type CSS and it worked perfectly.

    But I was concerned about browser compatibility. From what I’m reading, this pseudo class is pretty popular and works great in most browsers, including older versions. It seems the only one that’s somewhat of a concern is IE8. Is IE9 the most recent one? If so, then lots of people are probably still running IE8, right?

    Would some Javascript help make drop caps compatible in all browsers?

    Thank you!!

  2. Charlie
    Permalink to comment#

    For IE 8 && If youre using jQuery you can use:

    
    $('article p').first().css({fontSize:'1.25em'});
    
    

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".