Is there anyway to use the theme()
syntax for declaring a css variable with tailwind and using an opacity modifier after?
/*globals.css*/
@layer base {
:root {
/*these work fine*/
--almost-black: 12 12 12;
--body-color: var(--almost-black);
--sub-text-color: 107 114 128;
/*these break when used with opacity modifier syntax*/
--background-color: theme("colors.gray.50");
--color-primary: theme("colors.purple.600");
--color-secondary: theme("colors.purple.300");
}
}
// my tailwind config
const config: Config = {
...
theme: {
extend: {
colors: {
'body': 'rgb(var(--body-color))',
'sub-text': 'rgb(var(--sub-text-color))',
'background': 'rgb(var(--background-color))', // tried this just to sanity test but ofcourse it doesnt work because the output of `theme(colors)` is a hex value
'primary': 'var(--color-primary)',
'secondary': 'var(--color-secondary)',
}
},
},
};
Lets say I added this class to an element bg-body/50
Tailwind would know what I want and output some css like this
:is(.dark .dark\:bg-body\/50) {
background-color: rgb(var(--body-color) / 0.5);
}
But if I wanted to use this, there does not seem to be a way. You'll notice that that page mentions opacity syntax, however it does not speak about using it with a variable, only a hard coded value.
You could consider using the CSS-native color-mix()
function as part of the color values. This allows you to pass the <alpha-value>
through without needing to "know" the color at runtime or the need to have them in the component RGB/HSL format:
tailwind.config = {
theme: {
extend: {
colors: {
'body': 'rgb(var(--body-color))',
'sub-text': 'rgb(var(--sub-text-color))',
'background': 'color-mix(in srgb, var(--background-color) calc(100% * <alpha-value>), transparent)',
'primary': 'color-mix(in srgb, var(--color-primary) calc(100% * <alpha-value>), transparent)',
'secondary': 'color-mix(in srgb, var(--color-secondary) calc(100% * <alpha-value>), transparent)',
}
},
},
}
<script src="https://cdn.tailwindcss.com/3.4.4"></script>
<style type="text/tailwindcss">
@layer base {
:root {
/*these work fine*/
--almost-black: 12 12 12;
--body-color: var(--almost-black);
--sub-text-color: 107 114 128;
/*these break when used with opacity modifier syntax*/
--background-color: theme("colors.gray.50");
--color-primary: theme("colors.purple.600");
--color-secondary: theme("colors.purple.300");
}
}
</style>
<div class="bg-primary/75 w-10 h-10"></div>
<div class="bg-primary/50 w-10 h-10"></div>
<div class="bg-primary/25 w-10 h-10"></div>
<div class="bg-secondary/75 w-10 h-10"></div>
<div class="bg-secondary/50 w-10 h-10"></div>
<div class="bg-secondary/25 w-10 h-10"></div>