Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tailwind CSS color opacity with a variable not working

const Home = () => {
    const variableOpacity = 0.85;
    return (
        <>
            <main>
                <div className={`h-8 bg-primary/[${variableOpacity}]`}>85%</div> 
           </main>
        </>
    );
};

What I am trying to achieve here is to make a Progress bar where I need the background color of a div to change as per a variable. I am using custom opacity like bg-primary/[0.85] and when I type this in the div it works but it doesn't work using a variable with same value as in the code sample. Actually, it works when the variable's value is 0.3 but it doesn't work for any other values.

My Tailwind Config enter image description here

like image 767
Nirzal Avatar asked Apr 21 '26 00:04

Nirzal


1 Answers

Creating dynamic classes in tailwind won't work. That's because tailwind searches for your classes during build time and will only bundle the classes that it explicitly finds on source code.

The solution for what you want to do is to use the style props instead. Something like this:

const Home = () => {
    const variableOpacity = 0.85;
    return (
        <>
            <main>
                <div
                    className={'h-8'}
                    style={{backgroundColor:`rgba(51, 170, 51, ${variableOpacity})`}}
                >85%</div> 
            </main>
        </>
    );
};

Of course, as you have seen, you must specify the color in rgb notation (values in range 0-255 and opacity in range 0-1).

like image 52
Feder 240516 Avatar answered Apr 23 '26 17:04

Feder 240516



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!