In a sentence: Why does calculations with JS variables does not apply any style using TailwindCSS v3?
I am using VueJS for my project, and this example works as expected as it simply applies calc as string:
...
<div class="w-[calc((100%-12rem)*2/3)]">
...
While this doesn’t (there are JS variables involved):
...
<div :class="`w-[calc(${props.languages.length * 1.25 + 3}rem)]`">
...
When I inspect the console, I can see HTML with the correct class:
...
<div class="flex w-[calc(14.25rem)]"
...
… but styles are not applied. Any ideas? What am I doing wrong? I think this is a very powerful feature as it lets you dynamically style your HTML based on underlying data, but I can’t make it work although I think am so close.
Thanks in advance.
2
Answers
I finally found the cause: Tailwind's JIT, which is enabled and working by default in TailwindCSS v3.
Here is the interesting part: they say not to construct class names dynamically, which is precisely what I was trying to do.
So I finally followed their recommendation (see this very useful v2 docs link) and bypassed Tailwind for one time, directly using a
style
attribute to set thewidth
of my element like this:Thanks anyway ;)
Do this instead:
Equivalent in Vue: