How to Use :last-child in CSS for Targeting Last Elements
Use the
:last-child CSS pseudo-class to select the last element among its siblings inside a parent. It applies styles only to the very last child element of its parent container.Syntax
The :last-child selector targets an element that is the last child of its parent. It is written by adding :last-child after the element or class selector.
element:last-childtargets the last child if it matches the element type..class:last-childtargets the last child if it has the class.
css
selector:last-child {
property: value;
}Example
This example shows how to color the last item in a list red using :last-child. Only the last list item gets the red color.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Last-child Example</title> <style> ul li:last-child { color: red; font-weight: bold; } </style> </head> <body> <ul> <li>First item</li> <li>Second item</li> <li>Last item</li> </ul> </body> </html>
Output
A bulleted list with three items: 'First item', 'Second item', and 'Last item'. The last item text is red and bold.
Common Pitfalls
One common mistake is expecting :last-child to select the last element of a certain type regardless of siblings. It only matches if the element is truly the last child of its parent.
For example, li:last-child will not select an li if it is not the last child, even if it is the last li.
css
/* Wrong: This will not style the last li if it's not the last child */ ul li:last-child { color: blue; } /* Right: Use :last-of-type to select last li regardless of other siblings */ ul li:last-of-type { color: blue; }
Quick Reference
- :last-child selects the last child element of its parent.
- It matches only if the element is the very last sibling.
- Use
:last-of-typeto select the last element of a specific type regardless of other siblings. - Works with any element type and class selectors.
Key Takeaways
Use
:last-child to style only the last child element inside a parent.:last-child matches only if the element is the very last sibling.If you want the last element of a type regardless of siblings, use
:last-of-type instead.Works with any element or class selector by appending
:last-child.Common mistake: expecting
:last-child to select the last element of a type when it is not the last child.