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.

Categories: web designing css

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo