What is the difference between :first-child and :first-of-type in CSS?

In this article we will talk about the important difference that exists between two CSS selectors whose purpose is to select the first element of a series.

:first-child selects the first descendant of a parent if and only if the element appears in the source as the first descendant regardless of type.

Having this HTML structure:

<div class="parent">
   <p></p>
   <p class="special"></p>
   <p class="special"></p>
</div>

With :first-child we can write:

.parent > p:first-child {
     color: green;
}

We will obtain the desired effect, because the only p element without the .special class is found in the source exactly in the position of the first descendant of its parent.

If instead we wanted to select the first element with class .special regardless of its position in the source but only by virtue of the fact that it has this class, we must use the selector :first-of -type:

.parent .special:first-of-type {
     color: green;
}

In practice, with the first selector we are bound to the source order while with the second the constraint is that of being the first element of a series that has certain characteristics.

Back to top