DEV Community

Cover image for CSS Pseudo Selectors: What's the difference between :first-of-type and :first-child
John Palmgren
John Palmgren

Posted on

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>
Enter fullscreen mode Exit fullscreen mode

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay