Last active
January 5, 2022 19:02
-
-
Save bryanmylee/86d145a99b0e9a7d15c8776b77845336 to your computer and use it in GitHub Desktop.
TailwindCSS variable colors with `bg-opacity`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const colors = require('tailwindcss/colors'); | |
/** Colors must be defined in a special format. | |
--color-s-0: 255, 255, 255; | |
--color-s-50: 248, 250, 252; | |
--color-s-100: 241, 245, 249; | |
--color-s-200: 226, 232, 240; | |
--color-s-300: 203, 213, 225; | |
--color-s-400: 148, 163, 184; | |
--color-s-500: 100, 116, 139; | |
--color-s-600: 71, 85, 105; | |
--color-s-700: 51, 65, 85; | |
--color-s-800: 30, 41, 59; | |
--color-s-900: 15, 23, 42; | |
*/ | |
module.exports = { | |
important: true, | |
theme: { | |
colors: { | |
s: { | |
0: 'rgb(var(--color-s-0))', | |
50: 'rgb(var(--color-s-50))', | |
100: 'rgb(var(--color-s-100))', | |
200: 'rgb(var(--color-s-200))', | |
300: 'rgb(var(--color-s-300))', | |
400: 'rgb(var(--color-s-400))', | |
500: 'rgb(var(--color-s-500))', | |
600: 'rgb(var(--color-s-600))', | |
700: 'rgb(var(--color-s-700))', | |
800: 'rgb(var(--color-s-800))', | |
900: 'rgb(var(--color-s-900))' | |
}, | |
// colors that are not rgb(...) are unaffected | |
// also the plugin could easily be extended to check for hex with only 3 or 6 values instead of 4 or 8 | |
green: colors.green | |
}, | |
plugins: [ | |
function ({ addUtilities, theme, variants }) { | |
const fn = (prefix, key, prop, opacity) => { | |
const t = theme(prop); | |
addUtilities(Object.keys(t) | |
.reduce((_o, _k) => ({ | |
..._o, | |
...Object.keys(t[_k]) | |
.filter(x => /^rgb\(.*\)$/i.test(t[_k][x])) | |
.reduce((o, k) => ({ | |
...o, | |
[`.${prefix}-${_k}-${k}`]: { | |
[opacity]: '1', | |
[key]: t[_k][k].replace(/^rgb\((.*)\)$/i, `rgba($1, var(${opacity})) !important`) | |
} | |
}), {}) | |
}), {}), { | |
respectImportant: false, | |
variants: variants(prop) | |
}); | |
} | |
// add more utils here... | |
fn('bg', 'background-color', 'backgroundColor', '--tw-bg-opacity'); | |
fn('text', 'color', 'textColor', '--tw-text-opacity'); | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment