Search code examples
javascripttailwind-csstailwind-in-jsmodule-export

Tailwind CSS: Referencing to custom color in tailwind.config.js


In order to streamline my theming I'd like to reference to a custom color I defined and then pass it through a function to get a lighter or darker variant.

I extend the default color theme using the following (partial) code:

module.exports = {
    theme: {
        extend: {
            colors: {
                primary: {
                    DEFAULT: '#325889',
                    light: '#5aacbb',
                    lighter: '#5ebebf',
                },
            },
        },
    },
}

Now my goal is to somehow reference the colors.primary in another custom color variant to pass it into a custom function, something like this:

module.exports = {
    theme: {
        extend: {
            colors: {
                primary: {
                    DEFAULT: '#325889',
                    light: '#5aacbb',
                    lighter: '#5ebebf',
                },
                gradient: {
                    '0\/3': this.theme.extend.colors.primary,
                    '1\/3': getGradientStop(this.theme.extend.colors.primary, this.theme.extend.colors.primary.lighter, 33.333),
                    '2\/3': getGradientStop(this.theme.extend.colors.primary, this.theme.extend.colors.primary.lighter, 66.666),
                    '3\/3': this.theme.extend.colors.primary.lighter,
                }
            },
        },
    },
}

However, I can't seem to reference the primary color in any way. I tried this.colors.primary, this.theme.extend.colors.primary but can't seem to get it up and running.

Any clues on how to do this would be greatly appreciated.

Cheers!


Solution

  • You can create new variable to keep the value of your extended colors:

    const primary = '#325889';
    const primaryLight = '#5aacbb';
    const primaryLighter = '#5ebebf';
    
    module.exports = {
        theme: {
            extend: {
                colors: {
                    primary: {
                        DEFAULT: primary,
                        light: primaryLight,
                        lighter: primaryLighter,
                    },
                    gradient: {
                        '0\/3': primary,
                        '1\/3': getGradientStop(primary, primaryLighter, 33.333),
                        '2\/3': getGradientStop(primary, primaryLighter, 66.666),
                        '3\/3': primaryLighter,
                    }
                },
            },
        },
    };