Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rand.thacker's avatar

Vite not building dynamic CSS classes

I'm wondering how to handle dynamically generated CSS class names in a blade template. I want to use Tailwind, and stick to the conventions/examples, etc. I'm using the latest Laravel (9.28 at the time of the question). Let's say I have a div such as this: <div draggable='true' class="mx-2 bg-green-{{ $level }}">Item</div> OR <div class="grid-cols-{{ $number_of_days }}">

And the possible $level values, based on the blade loop/logic are 300 or 500 (for instance), and $number_of_days can be like 5 or 7 (again, these are both just examples of classes that will be dynamically chosen by code)

When I npm run build, because the bg-green-300 or bg-green-500 (or grid-cols-5 and grid-cols-7) are never explicitly mentioned in the blade template, apparently, the classes for those are never added to the resulting CSS.

Am I approaching this entirely the wrong way or am I missing something in the build/vite config?

0 likes
4 replies
rand.thacker's avatar

@Sinnbeck thank you so much for your quick answer! Thanks for pointing me at safelist - that's exactly what I needed!

thinkverse's avatar

@rand.thacker as @sinnbeck suggested, use the safelist. I just wanted to add on and say that Tailwind CSS itself doesn't support dynamic classes, it's not necessarily Vite that doesn't handle them correctly.

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

This is a section from the same documentation page, just slightly above titled, very appropriately dynamic class names, where the documentation explicitly mentions to don't construct class names dynamically as per your example.

Also to add on a bit, your use-case could've worked if the class was compiled to a full string before Tailwind CSS parsed the file. This, in Laravel's case, doesn't work since Tailwind parses the un-compiled views located in the resources/views folder, so Tailwind's parser will be looking for a class names grid-cols-{{ $number_of_days }} and not grid-cols-7 for instance.

1 like
kelnorman's avatar

It's good that you got an answer to your question.

Please or to participate in this conversation.