Open In App

CSS :last-child Selector

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The CSS :last-child selector targets the last child element within its parent. It applies styles exclusively to the last child based on its position within the parent container, regardless of the element type or class. If the parent element is missing or incorrectly structured, the selector will not function as intended, because there is no defined parent-child relationship to reference.

Syntax

:last-child {
//property
}
HTML
<html>
<head>
    <style>
        p:last-child {
            background: limegreen;
            color: white;
            font-style: italic;
            font-size: 1.875em;
        }
    </style>
</head>
<body>
    <p>I am first child.</p>
    <p>I am second child.</p>
    <p>I am third child.</p>
    <p>I am last child.</p>
</body>
</html>

In this case, the styles are applied to the last <p> tag in the <body> container.

Output:

How Does the :last-child Selector Work?

The :last-child selector works based on the position of an element within its parent container. To understand this better, let’s break it down:

  • The :last-child selector selects an element that is the last child of its parent element.
  • This applies regardless of the element type. For example, the last paragraph (<p>) inside a <div> or the last list item (<li>) inside a <ul> can be selected.

However, only the last element that is a direct child of the parent element will be targeted. If you have nested elements, the :last-child selector doesn’t target inner elements but the last child at the same level of hierarchy.

What Happens If There’s a Missing Parent?

The :last-child selector depends on the parent-child relationship. If the parent element is missing or if the elements are not properly nested, the selector won’t work as expected. For instance, if you forget to place elements inside a parent container, the :last-child selector will not target anything.

Supported Browsers:


Next Article

Similar Reads