The :first-child selector selects an element that is the first child of its parent element. For example, if you use p:first-child
, it will select every paragraph that is the first child of its parent.
The :first-of-type selector on the other hand selects every element that is the first element of its type within its parent. For example, if you use p:first-of-type
, it will select every first paragraph inside its parent but the important thing here is that this paragraph needs not to be the first child.
It can be the 2nd child of its parent but must be the first of its type i.e. of type paragraph.
Getting confused? See the following working example:
Example:
p:first-child{ background: pink; } h4:first-of-type{ background: yellow; }
If you have noticed, in the above example, the first <h4>
got a yellow background even if it was the second child of the div element.
This is because the :first-of-type
selector always targets the first element of its type regardless of its position in the parent. That is, it is not necessary that the element should be the first child of its parent.