Role of CSS :last-child Selector

The CSS :last-child selector is a pseudo-class that targets an element that is the last child of its parent container. This selector is commonly used to apply specific styles to the final element in a group, such as removing bottom margins or adding special formatting.

Syntax

selector:last-child {
    property: value;
}

Example: Styling Last Paragraph

The following example demonstrates how to style the last paragraph element with an orange background −

<!DOCTYPE html>
<html>
<head>
<style>
    p:last-child {
        background-color: orange;
        padding: 10px;
        border-radius: 5px;
    }
</style>
</head>
<body>
    <p>This is demo text1.</p>
    <p>This is demo text2.</p>
    <p>This is demo text3.</p>
</body>
</html>
Three paragraphs appear on the page. The first two paragraphs have default styling, while the third paragraph (last child) has an orange background with padding and rounded corners.

Example: Removing Bottom Margin from Last Item

A common use case is removing the bottom margin from the last element in a list −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        border: 2px solid #333;
        padding: 20px;
        width: 300px;
    }
    
    .item {
        background-color: #f0f0f0;
        padding: 10px;
        margin-bottom: 15px;
    }
    
    .item:last-child {
        margin-bottom: 0;
    }
</style>
</head>
<body>
    <div class="container">
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
    </div>
</body>
</html>
A container with three items appears. Each item has a gray background and padding. The first two items have a 15px bottom margin, while the last item has no bottom margin, creating a cleaner container edge.

Conclusion

The :last-child selector is essential for creating polished layouts by targeting the final element in a container. It's particularly useful for removing unwanted margins and applying special styling to closing elements.

Updated on: 2026-03-15T12:20:47+05:30

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements