:first-of-type

The :first-of-type pseudo-class applies the given style to an element that is the first child of a certain type within a parent element.

 

The pseudo-class first-of-type selects the element that is the first child of the parent of the given type. 

That is, if you write span:first-of-type – it will select the first span in the parent (unlike first-child, which will select only the span that is the very first in the parent).

The difference between the :first-of-type pseudo-class and :first-child is that it selects the first child of a particular type, not the first child of that type.

Syntax

/* Apply custom style to the first <section> element */

section :first-of-type { 
    color: white;
    background-color: orange; 
}

Example

Consider an example where the main content of the page is wrapped in <div> blocks that have the .example style class, and you need to style the first paragraphs (<p> elements) in these blocks in some way:

Heading #1

First paragraph

Second paragraph

Heading #2

First paragraph

Second paragraph

HTML

<div class="example">
    <h4>Heading #1</h4>
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>
<div class="example">
    <h4>Heading #2</h4>
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>

CSS

.example p:first-of-type  {
    color: white;
    background-color: orange;
    font-weight: 300;
}