Difference Between :last-child and :last-of-type Selector in CSS
Both Selectors are used to select the last child element of an HTML. Web designers got confused between them, in this blog you will get understand the difference between both selectors.
:last-child: This selector is used to select the last child of the selected parent element. It does not match the element type.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
li:last-child
{
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>
<li>list4</li>
<h3>first child</h3>
</ul> </body> </html>
In the above example, last-child: it will select li of the second ul because the first ul’s last child is h3.
:last-of-type: This selector is used to select the last child of the selected parent element. It matches the element type.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
li:last-of-type
{
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>
<li>list4</li>
<h3>first child</h3>
</ul> </body> </html>
In the above example, last-of-type: it will select the last li of both the ul’s element.