Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
The:last-child selector not working as expected in HTML5
The :last-child CSS selector selects an element only if it is the last child of its parent, regardless of type or class. A common mistake is expecting it to select the last element of a specific type or class within a parent, but that is not how it works. This is why :last-child often does not behave as expected.
When :last-child Works
The :last-child selector works when the target element is literally the very last child of its parent. For example, if your selector is a:last-child, it matches only if an <a> tag is the last child inside its parent ?
Example: :last-child Works
<!DOCTYPE html>
<html>
<head>
<style>
a:last-child {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<div>
<a href="#">First link</a>
<a href="#">This will be selected</a>
</div>
</body>
</html>
This works because the second <a> is the last child of the <div>.
When :last-child Fails
It creates issues if the element is not the very last child of its parent. For example, if a <p> tag comes after the <a> tags, then a:last-child will not match anything because the last child is a <p>, not an <a> ?
Example: :last-child Fails
<!DOCTYPE html>
<html>
<head>
<style>
a:last-child {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<div>
<a href="#">First link</a>
<a href="#">Second link (NOT selected)</a>
<p>This paragraph is the actual last child</p>
</div>
</body>
</html>
No <a> tag gets the blue background because the last child of the <div> is a <p>, not an <a>.
The Fix: Use :last-of-type
If you want to select the last element of a specific type (regardless of what comes after it), use :last-of-type instead ?
Example: :last-of-type Works
<!DOCTYPE html>
<html>
<head>
<style>
a:last-of-type {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<div>
<a href="#">First link</a>
<a href="#">This WILL be selected</a>
<p>This paragraph does not interfere</p>
</div>
</body>
</html>
Now the second <a> gets the blue background because :last-of-type selects the last <a> element among its siblings, regardless of other element types that follow it.
Conclusion
The :last-child selector only matches if the element is the absolute last child of its parent. If other elements follow it, use :last-of-type instead to select the last element of a specific type.
