0
0
CssHow-ToBeginner · 3 min read

How to Select Last Child in CSS: Simple Guide

Use the :last-child pseudo-class in CSS to select the last child element of its parent. For example, p:last-child targets the last <p> inside its parent container.
📐

Syntax

The :last-child selector targets an element that is the last child of its parent. It is written by placing :last-child after the element selector.

  • element:last-child - selects the last child if it matches the element type.
  • :last-child alone - selects any element that is the last child.
css
selector:last-child {
  property: value;
}
💻

Example

This example shows how to style the last <li> item in a list with a different 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 its position. It only matches if the element is truly the last child of its parent.

For example, p:last-child will not select a <p> if it is not the last child, even if it is the last <p> among siblings.

css
/* Wrong: This will not select the last <p> if it is not the last child */
p:last-child {
  color: blue;
}

/* Correct: Use :last-of-type to select the last <p> regardless of position */
p:last-of-type {
  color: blue;
}
📊

Quick Reference

  • :last-child - selects the last child element of its parent.
  • :last-of-type - selects the last child of its type regardless of other siblings.
  • Use :last-child when you want to style the very last element inside a container.

Key Takeaways

Use :last-child to select the very last child element of a parent.
:last-child only matches if the element is the last child, not just the last of its type.
For the last element of a specific type, use :last-of-type instead.
Always test your selectors in the browser to confirm they target the right elements.
Combine :last-child with other selectors for precise styling.