tailwindcss-color-mix
Live demo
A plugin for TailwindCSS to build new colors by mixing two existing ones.
Use bg-red-500 bg-mix-black bg-mix-amount-50
to partially overlay black
over the red-500
shade.
This is achieved with native CSS color-mix, so all colors in the palette can be mixed with each other.
Installation
First, install the package:
npm install --save tailwindcss-color-mix
Then, import it in tailwind.config.js
:
const colorMix = require('tailwindcss-color-mix');
module.exports = {
...
plugins: [
...,
colorMix()
]
}
Usage
bg-red bg-mix-black bg-mix-amount-50
will mix 50% black into red.
- In CSS terms, the result will be
color-mix(in srgb, black 50%, red)
.
You can also use arbitrary values for amount such as bg-mix-amount-[42]
(for 42%).
The default mix amount is zero.
Interpolation method
Default interpolation method is srgb
but you can also use hsl shorter hue
or hsl longer-hue
with the bg-mix-method-shorter-hue
and bg-mix-method-longer-hue
utilities.
Example: interaction states
The plugin is usage-agnostic, but the original motivation behind it is the state layers concept from the Material Design system.
The system defines interactive surfaces given their background color and their text color. When hovered or pressed, the background on an interacive surface is overlayed with a predetermined opacity of its text color. This helps to create consistent interaction states with no extra effort.
In vanilla Tailwind syntax, that would force us to define extra shades for every combination of background and text colors we need.
With this plugin, an interactive surface can be defined as bg-red-800 text-white bg-mix-white hover:bg-mix-amount-8 active:bg-mix-amount-12
, if 8
and 12
exist in the background opacity theme config.
Plugin options
You can customize the generated utility names by passing options to the plugin, like this:
tailwind.config.js
:
const colorMix = require('tailwindcss-color-mix');
module.exports = {
...
plugins: [
...,
colorMix({
bgMix: 'bg-overlay',
bgMixAmount: 'overlay-amount',
bgMixMethod: 'overlay-method'
})
]
}
With the above configuration, instead of bg-mix-black bg-mix-50 bg-mix-method-shorter-hue
, you would use bg-overlay-black overlay-amount-50 overlay-method-shorter-hue
.
Other color properties
I haven't found the need to extend this library to other properties such as text color, border, fill, stroke, ring... but it shouldn't be hard to do so. Feel free to open a feature request if you need color mixing on one or more specific properties.