One of the last pieces when moving a Sass codebase to vanilla CSS was to replace the darken()
and lighten()
color functions in Sass. Now it’s easier than before. There are good browser support for both color-mix()
and the oklch()
color space. A quick example:
/* Darken background color in CSS, two options
Instead of using Sass lighten() and darken()
Urban Sanden 2024
*/
@layer demo;
@layer demo {
:root {
--first-color: hotpink;
--second-color: slateblue;
}
.first {
background-color: var(--first-color);
}
.second {
background-color: var(--second-color);
}
.first:hover {
/*
Works across the latest devices and browser versions since 2023.
The color-mix() functional notation takes two <color> values and returns the result of mixing them in a given colorspace by a given amount.
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix
*/
background-color: color-mix(in srgb, var(--first-color), #000 20%);
}
.second:hover {
/*
Works across the latest devices and browser versions since 2023.
The oklch() expresses a given color in the Oklab color space. oklch() is the cylindrical form of oklab(), using the same L axis, but with polar Chroma (C) and Hue (h) coordinates.
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch
*/
background-color: oklch(from var(--second-color) calc(l - 0.2) c h);
}
}