Using :not() selector in Tailwind CSS

Updated: December 15, 2023 By: Khue Post a comment

In CSS, you can use the :not() pseudo-class to style elements that do NOT match one or multiple specified elements/selectors. In Tailwind CSS 3.1 (released in June 2022 – a long time ago) and newer, you can do the equivalent thing as follows:

[&:not(your selector)]:<utility class>

For more clarity about this, see example 1.

In case you want to use the :not() selector from the parent element, you can do like so:

<div class="[&>:not(your selector)]:<utility class>">
    <!-- List of child elements here -->
</div>

See example 2 for a better understanding.

Example 1

This example makes all <h1> elements have the text color blue, and all other elements’ text will be red.

Screenshot:

The code:

<html>

<head>
    <title>Sling Academy</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-sky-100 p-40">
    <h1 class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">SlingAcademy.com</h1>
    <h2 class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">Banana</h2>
    <h3 class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">Apple</h3>
    <p class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">Water Melon</p>
    <div class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">Robot</div>
    <h1 class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">Another H1</h1>
</body>

</html>

Example 2

This example uses the :not() selector in the parent element. Child elements other than <p> will have blue text and large font sizes.

Screenshot:

The code:

<body class="bg-amber-100 p-40">
    <div class="[&>:not(p)]:text-blue-500 [&>:not(p)]:text-4xl">
        <h1>Sling Academy</h1>
        <p>Puppies are small and cute</p>
    </div>
</body>

That’s if. Happy coding & have fun with Tailwind CSS.