You might have been in a situation where you’re forced or would prefer to write vanilla CSS in a Tailwind project.
In my case, I wanted to write some animation code involving multiple keyframes, and pseudo-elements, and implementing it in Tailwind resulted in a class name that’s very long and hard to read, so I reached out to vanilla CSS instead.
That’s when I ran into a problem. I also wanted to use colors and spacing from my Tailwind configs. For example, instead of hard coding the red color
#dc2626 in my CSS file, I wished I can use Tailwind’s
bg-red-600. And fortunately, there’s a solution.
To solve this issue, we can use the
theme() utility function from Tailwind. There’s no need to import or configure anything, just use it directly in your CSS file.
You can also use it for CSS variable like this:
Tips: If you use Tailwind’s Intellisense, you’ll also get auto complete inside
How It Works
So how does it work?
On build time, Tailwind will replace all the
theme() calls with static value.
That’s it for this post. Hope you find it useful.
One final thing, this trick not only works in Vanilla CSS but also in scoped CSS in frontend frameworks like Vue, Svelte, Astro, etc.