Open In App

CSS :not(:last-child):after Selector

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The :not(:last-child):after selector is used to apply styles to elements that are not the last child of their parent and also apply an :after pseudo-element.

  • It is helpful for adding visual separators (e.g., lines or dots) between items while excluding the last item.
  • Combines the power of :not() and :after for better styling control.

Syntax:

element:not(:last-child)::after {
content: " ";
/* Additional styling properties */
}
HTML
<html>
<head>
    <style>
        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        li:not(:last-child):after {
            content: '|';
            margin: 0 10px;
            color: gray;
        }
    </style>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>
</html>
  • The :not(:last-child):after selector adds a | after each list item except the last one.
  • The margin creates space between the content and the separator.

More Example of CSS :not(:last-child):after Selector

Dotted Separator Between Spans

HTML
<html>
<head>
    <style>
        .container span:not(:last-child):after {
            content: ' • ';
            color: blue;
        }
    </style>
</head>
<body>
    <div class="container">
        <span>Home</span>
        <span>About</span>
        <span>Contact</span>
    </div>
</body>
</html>
  • The :not(:last-child):after adds a blue dot between spans.
  • The last span has no pseudo-element added, making it clean.

Adding a Hyphen Between List Items

HTML
<html>
<head>
    <style>
        ul li:not(:last-child)::after {
            content: ' -';
            color: #888;
        }
        ul {
            list-style: none;
            padding: 0;
        }
        li {
            display: inline;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Cherry</li>
    </ul>
</body>
</html>
  • The :not(:last-child)::after selector appends a hyphen – after each list item except the last, creating a simple inline list with separators.


Next Article

Similar Reads