I am trying to learn how to do themes in tailwind CSS for a laravel project. Stuck on how to add opacity in the theme
//app.css file
@layer base {
:root {
/* Brand Color */
--color-element-primary: #5754FF;
--color-element-soft-hover: #5754FF; /* 15% */
/* Text */
--color-text-primary: #FFFFFF;
--color-text-content:#FFFFFF; /* 80% */
--color-text-muted:#7C879F; /* 45% */
Than in the tailwind.config.js
file I setup things like this
extend: {
fontFamily: {
sans: ["General Sans", ...defaultTheme.fontFamily.sans],
},
colors: {
theme: {
'primary': 'var(--color-element-primary)',
'primary-soft-hover': 'var(--color-element-primary-soft-hover)',
}
},
textColor: {
theme: {
primary: 'var(--color-text-primary)',
content: 'var(--color-text-content)',
muted: 'var(--color-text-muted)',
}
},
This allows me to use it inside the project like this
But I want to make the opacity values dynamic to the themes. Any insight on how to set this up is much appreciated :)
I was looking to use the a theme color with opacity utilities (like bg-primary/25
) from the framework. Not sure if that is the question here?
In case it is I came across this functions, which works for me:
const getColor = (colorVar, { opacityVariable, opacityValue }) => {
if (opacityValue !== undefined) {
return `rgb(var(${colorVar})/${opacityValue})`;
}
if (opacityVariable !== undefined) {
return `rgb(var(${colorVar})/var(${opacityVariable}, 1))`;
}
return `rgb(var(${colorVar}))`;
};
and apply it like so in your source tailwind.config.js
theme: {
colors: {
primary: (params) => getColor("--color-primary", params)
}
}
Now you can define the --color-primary
variable in your css file and it will change accordingly.