Difference Between :first-child and :first-of-type Selector in CSS

Difference Between :first-child and :first-of-type Selector in CSS

Both Selectors are used to select the first child element of an HTML. Web designers got confused between them, in this blog you will get understand the difference between both selectors.

:first-child: This selector is used to select the first child of the selected parent element. It does not match the element type.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
 
li:first-child
{
   color:red;
}

</style>
</head>
 
<body>
 
<ul>
<h3>first child</h3>
<li>list1</li>
<li>Courses
<ul>
<li>Web Design</li>
<li>Web Development</li>
<li>Graphic Design</li>
<li>Video Editing</li>
</ul>
</li>
<li>list3</li>
<li>list4</li>
</ul>
 
</body>
</html>
 

In the above example, first-child: it will select li of the second ul because the first ul’s first child is h3.


:first-of-type:
This selector is used to select the first child of the selected parent element. It matches the element type.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
 

 
li:first-of-type
{
   color:red;
}
 
</style>
</head>
 
<body>
 
<ul>
<h3>first child</h3>
<li>list1</li>
<li>Courses
<ul>
<li>Web Design</li>
<li>Web Development</li>
<li>Graphic Design</li>
<li>Video Editing</li>
</ul>
</li>
<li>list3</li>
<li>list4</li>
</ul>
 
</body>
</html>
 

In the above example, first-of-type:  it will select the first li of both the ul’s element.