What is the correct way to build multi-color template using Tailwind CSS?

Viewed 127

Creating a custom color scheme for a template is very easy in Tailwind CSS. You just modify tailwind.config.js, add your custom color palate, and use it just like Tailwind's ordinary classes. For example bg-brand-500:

    theme: {
        extend: {
            colors: {
                brand: {
                    '50': '#B0ECEC',
                    '100': '#A0E8E8',
                    '200': '#7FE1E1',
                    '300': '#5ED9D9',
                    '400': '#3DD1D1',
                    '500': '#2CB9B9',
                    '600': '#218C8C',
                    '700': '#165E5E',
                    '800': '#0C3131',
                    '900': '#010404'
                },
            }
        }
    }

Now I'm stuck at a way to make a multi-color template.

I'm sure you have all seen templates all over the web where you can choose red or blue for example and the entire template's color scheme changes.

How do you do that in Tailwind?

Update: In other CSS schools, like SASS, you simply create another color variables file and dynamically load a different file using the regular <link href='/path/to/red/variables.css' />.

1 Answers

You can use CSS variables for that.

In your tailwind config, you create the brand colors as you did, but instead of hex color codes, you use for example 50: 'var(--brand-50)'. Then in your index.css you can add these variables to the base layer, like:

@layer base {
    :root {
        --brand-50: #B0ECEC;
    } 
    .theme-red {
        --brand-50: #BB0000;
    }
}

Now, if you add the class .theme-red to your body, text-brand-50 will be red.

In this video of Tailwind labs it is fully explained. There is also explained how to deal with opacity, although since tailwind 3.1 there is an easier way of doing that.

Hope this helps.

Related