Calculating the complementary color in CSS
I'm currently rebuilding the design of my blog and want to use a complementary color palette. As I'm not yet sure which colors I will use it would be ideal to automatically derive the secondary color from the primary color.
In the future this can be done using the relative color feature coming to CSS, but this isn't yet widely supported.
--primary: hsl(170, 66%, 28%);
--secondary: hsl(from var(--primary) calc(h + 180) s l);
I figured out that you can achieve the same effect using the color-mix. This is already supported by all major browsers.
--primary: hsl(170, 66%, 28%);
--secondary: color-mix(in hsl longer hue, var(--primary), var(--primary) 50%);
The command mixes the primary color with itself in the HSL color space. Additionally it is specified that it should use the longer pass along the hue axis. As this will always be the 360Β° path, a mix of 50% will end up at the 180Β° complementary color to the primary color. The saturation and lightness will stay the same.
This allows for fast testing of colors using the developer console:
This can also be used to create other color palettes by changing the percentage accordingly.