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

Asked

Viewed 1,030 times

5

I was writing a line of code and I was ready to type :first-of-type to change a certain element. That’s when I got the doubt: I must use first-of-type or first-child? Since both present the same result!

1 answer

3

See what the official documentation of W3C
https://www.w3.org/TR/selectors-3/

:first-Child (first child)

Same as :nth-child(1). The :first-child pseudo-class represents an element that is first in a list of siblings.

Translation: The same as: :nth-child(1). The pseudo-class: first-child represents an element that is the first of a list of siblings.


:first-of-type (first brother)

Same as :nth-of-type(1). The :first-of-typand pseudo-class represents an element that is the first sibling of its type.

Translation: The same as :nth-of-type(1). The pseudo-class first-of-type represents an element that is the first brother of its kind.


The priority and hierarchy value for the two is the same, so if the two are present at the same time what comes last will override the style of the first.

See this test with the classes, apparently there is no difference of priority in the classes, and briefly the first child and the first brother have the same weight and the same index

inserir a descrição da imagem aqui

Code of the image above

body {
    font-size: 20px;
}
p:first-of-type {
    color: red;
}

p:first-child {
    color: green;
}
<div>
    <p>Lorem ipsum dolor sit.</p>
    <h3>h3 aqui</h3>
    <p>Lorem ipsum dolor sit.</p>
    <p>Lorem ipsum dolor sit.</p>
    <div>
        <p>Lorem ipsum dolor sit.</p>
        <h3>h3 aqui</h3>
        <p>Lorem ipsum dolor sit.</p>
        <p>Lorem ipsum dolor sit.</p>
    </div>
</div>

  • 1

    Thank you for the examples and the explanation! :)

  • @Higustavo good that you helped there! If you believe that this answer solved your problem consider marking it as accepted in this icon . So it is not pending on the site as unresolved question. You can remove this vote at any time if you want, or put it in another answer that comes up and you think it suits you better. []s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.