Tailwind v4.1 introduced an easy way to handle safelisting CSS classes. Let’s take a look at that!
It’s as simple as using @source inline()
, and listing the class you want to whitelist.
For example, if Tailwind can’t find the text-shadow-md
class in our source files, but you still need it to generate in our CSS, you can do this:
@source inline("text-shadow-md");
Be Aware
Before we get to ahead of ourselves, I want to point out some things.
- You can’t use spaces inside of the
inline()
function. Unexpected results may occure if you do. - You should only define one class inside of each
@source inline()
. You’ll see below how we can get more classes out of one declaration, though. - Any CSS you define yourself or within
@layer
is automatically included in your generated CSS. - You can always define classes fully inside of a Javascript variable, array, switch statement, etc., and it will be included in your generated CSS.
I feel like the Tailwind docs on this don’t do a great job of explaining how all of this works, as it’s very easy to misunderstand.
Safelisting Multiple Classes
If we’re just safelisting basic classes, just write two separate statements:
@source inline("text-shadow-md");@source inline("float-left");
We can actually generate multiple classes out of one statement, as long as the prefix for the utility is the same:
@source inline("text-shadow-{sm,md,lg}");
For classes that involve numbers, we can do ranges.
@source inline("p-{2..10..2}");
This takes 3 arguments: the starting number, the ending number, and what to increment by.
This will generate the classes p-2
, p-4
, p-6
, p-8
, and p-10
.
We can also combine normal values and ranges:
@source inline("p-{50,{2..10..2},100}");
Safelisting Variants
You can also generate variant classes using any of the above examples:
@source inline("{hover:,}text-shadow-md");@source inline("{hover:,focus:,}float-left");
@source inline("{focus:,}text-shadow-{sm,md,lg}");
@source inline("{active:,}p-{2..10..2}");
@source inline("{nth-of-type-3:,}p-{50,{2..10..2},100}");
Excluding Classes
This concept is basically the opposite of whitelisting classes. You can also blacklist classes. You can use @source not inline()
to excluded CSS from being generated when they otherwise would be, and this will work with any of our examples above.
@source not inline("text-shadow-md");
I’m going to refrain from relisting every example above here with not inline()
, but you get the idea.
This article is a follow up to my previous article, which was released before Tailwind v4.1 was released. It may still be helpful if you have a more advanced use case.