This is a simple Tailwind plugin to expose all of Tailwind's colors, including any custom ones, as custom css properties on the :root
element.
There are a couple of main reasons this is helpful:
- You can reference all of Tailwind's colors—including any custom ones you define—from handwritten CSS code.
- You can define all of your colors within the Tailwind configuration, and access the final values programmatically, which isn't possible if you did it the other way around: referencing custom CSS variables (defined in CSS code) from your Tailwind config.
See the Tailwind Plugins for more info on plugins.
module.exports = {
theme: {
extend: {
colors: {
gray: {
'100': '#f5f5f5',
'200': '#eeeeee',
'300': '#e0e0e0',
'400': '#bdbdbd',
'500': '#9e9e9e',
'600': '#757575',
'700': '#616161',
'800': '#424242',
'900': '#212121',
},
},
},
},
plugins: [
function({ addBase, theme }) {
function extractColorVars(colorObj, colorGroup = '') {
return Object.keys(colorObj).reduce((vars, colorKey) => {
const value = colorObj[colorKey];
const newVars =
typeof value === 'string'
? { [`--color${colorGroup}-${colorKey}`]: value }
: extractColorVars(value, `-${colorKey}`);
return { ...vars, ...newVars };
}, {});
}
addBase({
':root': extractColorVars(theme('colors')),
});
},
],
};
A note to people stumbling on this gist as I did: This plugin is awesome, really nice idea, but consider adding variables to your CSS manually. Using something like the below, as long as you have access in your CSS to tailwind directives, you can reference colours and create variables from them:
For example, if you're using Next and following the globals.css pattern the docs describe you can add this to globals.css.
Doing it that way you don't need to worry about the bundle size reports others have mentioned (haven't looked at it myself, so no idea how badly it affects the size). Obviously the whole point of the plugin is quickly and easily provide access to all colours, but maybe you don't need that, so consider what you need contextually.