I would like the col-span-1 override col-span-2 however I'm trying to apply Tailwind CSS classes dynamically using a variable in my Svelte component.
Here's the code:
<script>
const hostClass = 'col-span-1';
</script>
<div class="col-span-2 {hostClass}">Test</div>
I expected col-span-1 from hostClass to override the static col-span-2 class, but it doesn't seem to work — the element keeps the col-span-2 style.
Is there a way to make col-span-1 override col-span-2?
As Brunnerh already mentioned, setting up an override system based on the order of classes is not relevant, because that's not how it works. CSS classes have their own strength based on specificity, which sometimes coincidentally gives you the result you want, and other times it doesn't.
For TailwindCSS, a utility called tailwind-merge
has been developed, which processes logic similar to what you're aiming for. Tailwind Merge is capable of merging multiple strings into one string while keeping only the last class of each TailwindCSS type. So in your example, it would keep the last added col-span-1
.
Utility function to efficiently merge Tailwind CSS classes in JS without style conflicts.
import { twMerge } from 'tailwind-merge' twMerge('px-2 py-1 bg-red hover:bg-dark-red', 'p-3 bg-[#B91C1C]') // → 'hover:bg-dark-red p-3 bg-[#B91C1C]'
Note: For TailwindCSS v3, you should use Tailwind Merge v2.
For TailwindCSS v4, you should use the latest Tailwind Merge v3.