DEV Community

Alan North
Alan North

Posted on

13 1

How to use Dynamic Variables with Tailwind

Have you ever wanted to do p-[${someDynamicValue}] in tailwind? Or maybe the more complicated after:content-[${someDynamicValue}]? Here's a better solution than resorting to a style tag.


Tailwind cannot have dynamic values in it's classes because the stylesheets are compiled at build time, neither the class name nor the value can be made up of dynamic variables for this to work.

This can be a bit of a pain in certain situations. One obvious solution is to move back to a style tag, but this means now the styles aren't all in one place, the main selling point of tailwind.

For certain situations, like p-[${someDynamicValue}] we can fallback to the style property:

<!-- I'm using vue here, but all frameworks have a way to do this. -->
<div
    :style="`padding:${someDynamicValue}`"
></div>
Enter fullscreen mode Exit fullscreen mode

But this is not always the case. Take after:content[${someDynamicValue}]. Style tags cannot target psuedo-elements, we have to resort to a style tag, or do we?

Style tags can have inline css variables. So we can actually do this:

<div
    class="after:p-[var(--customPadding)]"
    :style="`--customPadding:${someDynamicValue}`"
></div>
Enter fullscreen mode Exit fullscreen mode

Tailwind can now happily compile the class, it's name is no longer dynamic, it's .after\:p-\[var\(--customPadding\)\] and it's value is no longer dynamic, it's var(--customPadding). The part of the outputted css that we care about looks like this, here's a link to a demo on the playground.

.after\:p-\[var\(--customPadding\)\]::after {
    padding: var(--customPadding)
    //...
}
Enter fullscreen mode Exit fullscreen mode

And we can change the css variable to whatever we need. It's also very easy to find where the custom value was declared.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay