CSS Pseudo Selectors: What's the difference between :first-of-type and :first-child

CSS Pseudo Selectors: What's the difference between :first-of-type and :first-child

first-of-type and first-child are very similar pseudo selectors and will often target the same element. When they don't it can be confusing, so let's look at what they do.

First Child

first-child will look only at the first child element. In example one below .example-one div:first-child {} will select the first div. If we were to try that with example 2 and write .example-two div:first-child {} it would select nothing. This is because the first child is not a div, its a <h1>

<section class="example-one"> 
    <div></div>
    <div></div>
    <div></div>
</section>

<section class="example-two">
<h1>Hello World</h1>
<div></div>
<div></div>
</section>

First of Type

When you use the first-of-type pseudo selector it will select the first child element that matches that type. Consider the same code as above but with first-of-type.

example-one div:first-of-type {} will still select the first <div>. This is because it's the first child and the first of type.

example-two div:first-of-type {} doesn't select nothing, like it did with first-child but selects the second child which is the first element of type <div>

What's the difference?

There can be only one element that matches the first-child pseudo selector. This is because every parent element only has one element that is the first in that list.

For every parent element, there can be many fist-of-type elements. Every element that is the child of a parent element can be selected with the first-of-type pseudo selector.

illustration of first-of-type / first-child