Using Tailwind? Consider adding a prefix
19 Jan 2021Tailwind is rightly receiving all the attention it deserves. Every developer I've introduced it to falls in love with working with CSS again!
On a recent Nuxt project, I noticed a potential issue when using Tailwind class names.
Suddenly 'bg-green-500' didn't behave as expected, as an external component also using the same class had set the color to something else.
Workarounds such as adding !important unnecessarily will get into specificity and wars that inevitably end in tears.
Another workaround could be to use @apply and scoped styles, CSS modules or CSS-in-JS, but you lose some of the developer experience Tailwind offers.
Using scoped styles with Tailwind is easy and you can read how to do that with Vue, Next.js and Svelte.
Adding a prefix to Tailwind
However the simplest thing could be is to set a prefix in your Tailwind configuration file.
module.exports = {
prefix: 'tw-',
};
and then use the prefix for your tailwind classes so 'bg-green-500' becomes 'tw-bg-green-500'
<button
type="button"
class="tw-border tw-border-green-500 tw-bg-green-500 tw-text-white tw-rounded-md tw-px-4 tw-py-2 tw-m-2"
>
Success
</button>
You can see how to add a prefix below
Yes, there's still a chance of naming conflicts, but this is the best solution I can think of that keeps the awesome developer experience Tailwind with some level of safety without using @apply and scoped styles.
In my opinion, if you're building a component library in Tailwind, adding a prefix will save you and your users from styling conflicts.
If you're building a large app the earlier you start using a prefix the less headache you'll have of hunting down and changing Tailwind CSS classes later.