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 from your Tailwind config.
See the Tailwind Plugins for more info on plugins.
module.exports = {
theme: {
extend: {
colors: {
blue: {
'100': '#ebf6ff',
'200': '#b7ddff',
'300': '#85c2ff',
'400': '#51a5ff',
'500': '#2487ff',
'600': '#006aff',
'700': '#0755d4',
'800': '#164398',
'900': '#223867',
},
},
},
},
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')),
});
},
],
};
just to add some clarity to this otherwise amazing snippet, the colors are exposed as var(--color-color_name-intensity)
for example : var(--color-secondary-900)