Difference between :first-child and :first-of-type selector in CSS

Both of them are selectors for the HTML used in the CSS to select specific children.
The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <!DOCTYPE> must be declared for IE8 and earlier versions.

The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it’s parent. if we want to style the first child of an element without giving a class, we can use it.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>:first-child and first-of-type selector</title>
    <style>
        h1 {
            color: green;
        }
          
        h1,
        h2 {
            text-align: center;
        }
          
        p:first-child {
            background: red;
        }
          
        h4:first-of-type {
            background: green;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <h2>This is :first-child and first-of-type selector</h2>
    <div>
        <p>I am the First Child</p>
        <h4>I am the first of type Child</h4>
        <h4>I am the third Child</h4>
        <p>I am the fourth Child</p>
    </div>
  
</body>
  
</html>

chevron_right


Output:

Difference between :first-child and :first-of-type selector:

:first-child :first-of-type
This selector only choose the define element if the the element is the first child of the parent. If the define element comes second position then this selector can not select that element. This selector chose the define element if the element comes 2nd, 3rd or 4th any place but have to be the first of it’s type.
In the above example you can see inside the div tag the childs are p, h4, h4 and p. If you change 1st p tag into a another tag then :first-child slector can not select any child. In the above example you can see inside the div tag the childs are p, h4, h4 and p. If you change 1st p tag into h4 tag then :first-of-child slector will select the fisrt child of that parent which is also be the first child of the define element.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.