If I reference variables in CSS in a nested way using the var()
CSS function, it cannot properly track changes to the original variable. Is there a way in TailwindCSS to reference a value declared in @theme
without using var()
, so that the value is statically written into the desired place without relying on a variable?
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<style type="text/tailwindcss">
@theme inline {
--color-clifford: #da373d;
}
@layer components {
.example {
margin: --spacing(4);
width: --spacing(64);
height: --spacing(16);
background-color: var(--color-clifford);
}
}
</style>
<div class="example">Hello World by Component</div>
<div class="m-4 w-64 h-16 bg-clifford">Hello World by Utilities</div>
Generated CSS (check yourself: Playground)
In the case of a component, the background-color
is not a hardcoded static value but a variable:
.example {
background-color: var(--color-clifford);
}
Whereas in the case of the bg-clifford
utility, the hardcoded value is used as clarified in the question:
.bg-clifford {
background-color: #da373d;
}
I would like my component to also use the hardcoded value, and the expected generated CSS should look like this:
.example {
background-color: #da373d; /* instead of var(--color-clifford) */
}
.bg-clifford {
background-color: #da373d;
}
If you want to use hardcoded CSS instead of a variable in a given place, use TailwindCSS's built-in theme()
CSS function for that:
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<style type="text/tailwindcss">
@theme inline {
--color-clifford: #da373d;
}
@layer components {
.example {
margin: --spacing(4);
width: --spacing(64);
height: --spacing(16);
background-color: theme(--color-clifford); /* instead of var(--color-clifford) */
}
}
</style>
<div class="example">Hello World by Component</div>
<div class="m-4 w-64 h-16 bg-clifford">Hello World by Utilities</div>
Generated CSS (check yourself: Playground)
.example {
background-color: #da373d; /* what expected */
}
.bg-clifford {
background-color: #da373d;
}
Important: However, keep in mind that unlike var()
, theme()
can only be used statically. This means that at build time, Tailwind detects theme(--color-clifford)
in the source file and replaces it with the corresponding color code in the generated CSS, but afterwards it in no way behaves like var()
.