Using :not() selector in Tailwind CSS (2022)
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) and newer, you can do the equivalent thing as follows:
[&:not(your selector)]:<utility class>
For more clarity about this, see example 1.
If 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
Screenshot:

The code:
<body class="bg-sky-100 p-40">
<h1 class="text-blue-500 text-4xl [&:not(h1)]:text-red-500 [&:not(h1)]:text-2xl">KindaCode.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>
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>KindaCode.com</h1>
<p>Puppies are small and cute</p>
</div>
</body>
That’s if. Further reading:
- Full-Screen Search Box with Tailwind CSS
- How to Style Breadcrumb Navigation with Tailwind CSS
- Tailwind CSS: How to Create a Sticky Social Sharing Bar
- Text Overflow in Tailwind CSS (with Examples)
- Tailwind CSS: Use a Checkbox to Show/Hide an Element
- How to Rotate an Element in Tailwind CSS
You can also check out our CSS category page for the latest tutorials and examples.
Subscribe
0 Comments