CSS Basic
CSS :last-child Selector
Photo Credit to CodeToFun
🙋 Introduction
The :last-child
selector in CSS is a pseudo-class used to select the last element among a group of sibling elements.
This selector is especially helpful when you need to apply specific styles to only the last item in a list, row, or group without adding extra classes or IDs.
💡 Syntax
The signature of the :last-child
Selector is as follows:
element:last-child {
/* CSS properties */
}
The :last-child
selector can be applied to any type of element. It will target the last child element within its parent.
📝 Example 1:
Here is an example of how to use the :last-child
selector in CSS:
☠️ HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS :last-child Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</body>
</html>
🎨 CSS
/* Style for the last child of a list */
li:last-child {
color: red;
font-weight: bold;
}
In this example:
- The li:last-child selector targets the last list item (
<li>
) inside the<ul>
. - The last list item is styled with red text and bold font.
💬 Usage Tips
- The
:last-child
selector can be used with any element type. For example, you can apply it to paragraphs, divs, or table rows. - You can combine
:last-child
with other pseudo-classes or selectors for more specific styling. For instance, you could style only the last paragraph inside a div usingdiv p:last-child
.
📝 Example 2:
div p:last-child {
margin-bottom: 0;
}
This is especially useful when trying to remove spacing or apply different styles to the last element of a group.
⚠️ Common Pitfalls
- The
:last-child
selector targets the last child element of a parent, not necessarily the last element of a certain type. If you want to target the last element of a specific type within a parent, you should use :last-of-type instead. - Ensure that there are no hidden elements or non-visible nodes in the document that might unexpectedly be treated as the "last child."
🎉 Conclusion
The CSS :last-child
selector is a valuable tool for targeting the last element in a group without needing to modify the HTML structure. It simplifies styling and enhances flexibility, making it easy to manage last-child elements in dynamic content.
This selector is widely supported across modern browsers, making it a reliable option for precise layout and design control.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS :last-child Selector), please comment here. I will help you immediately.