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

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

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

Example:

<!DOCTYPE html>
<html>
<head>
<style>
 
li:nth-child(4)
{
   color:red;
}

</style>
</head>
 
<body>
 
<ul>
<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>
<h3>first child</h3>
<li>list4</li>
 
</ul>   </body> </html>   

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


:nth-of-type:
This selector is used to select the nth(n) child of the selected parent element. It matches the element type.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
li:nth-of-type(4)
{
   color:red;
}
 
</style>
</head>
 
<body>
 
<ul>
<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>
<h3>first child</h3>
<li>list4</li>
 
</ul>   </body> </html>   

In the above example, last-of-type:  it will select the 4th child of the selected 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 : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Related Blogs

Request For Demo