Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS calc() with TailwindCSS and JS variables

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.

like image 569
andcl Avatar asked Jun 19 '26 22:06

andcl


1 Answers

Do this instead:

<script src="https://cdn.tailwindcss.com"></script>

<div id="el" class="w-[calc(var(--languages-length)_*_1.25rem_+_3rem)] h-10 bg-red-300"></div>

<script>
el.style.setProperty('--languages-length', 6);
</script>

Equivalent in Vue:

<div 
 class="w-[calc(var(--languages-length)_*_1.25rem_+_3rem)] h-10 bg-red-300" 
 :style="{ '--languages-length': props.languages.length }"
></div>
like image 166
doğukan Avatar answered Jun 22 '26 01:06

doğukan