Avatar of Sara Cope
Sara Cope on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

Suppose we have an article and want to make the last paragraph smaller, to act as a conclusion to the content (like an editor’s note):

  <p>Lorem ipsum...</p>
  <p>Dolor sit amet...</p>
  <p>Consectetur adipisicing...</p>
  <p>Last paragraph...</p>

Instead of using a class (e.g. .last), we can use :last-child to select it:

p:last-child {
  font-size: 0.75em;

Using :last-child is very similar to :last-of-type but with one critical difference: it is less specific. :last-child will only try to match the very last child of a parent element, while last-of-type will match the last occurrence of a specified element, even if it doesn’t come dead last in the HTML. In the example above the outcome would be the same, only because the last child of the article also happens to be the last p element. This reveals the power of :last-child: it can identify an element with relation to all of its siblings, not just siblings of the same type.

The more complete example below demonstrates the use of :last-child and a related pseudo-class selector, :first-child.

Check out this Pen!

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Any 3.2+ Any 9.5+ 9+ Any Any

:last-child was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is impeccable, and the new pseudo-selectors are widely used in production environments. If you require older browser support, either polyfill for IE, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.