Home > database >  How do I reference CSS variable in Tailwind to define a custom class?
How do I reference CSS variable in Tailwind to define a custom class?

Time:12-05

I want to define a variable in a CSS file like this:

:root {
    --sidebar-width: 56;
}

I'd like to now refer to that in a component to define that component's width:

<div className="w-[var(--sidebar-width)]">
   <MySidebar>
</div>

This doesn't work. What I'm trying to achieve is to add the w-56 class to that component and to do so as a variable so that I can refer to that variable in several places. Is this possible and if so, how do I specify this?

CodePudding user response:

I'm pretty sure it's impossible.
Just do this instead:

:root {
    --sidebar-width: 56;
}

<div className="w-[calc(4px*var(--sidebar-width)]">
   <MySidebar>
</div>

1 tailwind unit is 4px.

CodePudding user response:

Tailwind does support CSS custom properties using arbitrary values.

:root {
    --sidebar-width: 56px;
}
<script src="https://cdn.tailwindcss.com"></script>
<div >Test</div>

  • Related