CSS :last-child

The CSS :last-child pseudo-class applies styles to the last child element of its parent. This pseudo-class is particularly useful for targeting and styling elements dynamically based on their position as the last child within their parent container.

The syntax for the :last-child pseudo-class is:

</>
Copy
selector:last-child {
    property: value;
}

Where:

ParameterDescription
selectorThe element you want to apply the :last-child pseudo-class to.
propertyThe CSS property to style the last child element.
valueThe value assigned to the CSS property.

Examples

1. Changing Text Color of the Last List Item

In this example, the text color of the last <li> in an unordered list is set to blue.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        li:last-child {
            color: blue;
        }
    </style>
</head>
<body>
    <ul>
        <li>First item</li>
        <li>Second item</li>
        <li>Last item</li>
    </ul>
</body>
</html>

2. Highlighting the Last Paragraph in a Section

Here, the last <p> element inside a <div> has a background color of lightgreen.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        div p:last-child {
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div>
        <p>First paragraph</p>
        <p>Last paragraph</p>
    </div>
</body>
</html>

3. Styling the Last Table Row

In this example, the background color of the last <tr> in a table is set to yellow.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        tr:last-child {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <table border="1">
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Last Row</td></tr>
    </table>
</body>
</html>

4. Changing Font Style of the Last Heading

The last <h2> in a container is styled with italic text and red color.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        h2:last-child {
            color: red;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div>
        <h2>Heading 1</h2>
        <h2>Last Heading</h2>
    </div>
</body>
</html>

5. Targeting the Last Child in a Nested List

In this example, the last child of a nested <ul> is styled with bold text and a larger font size.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        ul ul:last-child {
            font-weight: bold;
            font-size: 1.2em;
        }
    </style>
</head>
<body>
    <ul>
        <li>Parent Item 1
            <ul>
                <li>Child Item 1</li>
                <li>Child Item 2</li>
            </ul>
        </li>
        <li>Parent Item 2</li>
    </ul>
</body>
</html>