CSS introduced
contrast-color
Show archive.org snapshot
and it's available in modern browser versions. Here is a pure-CSS alternative for slightly older browsers.
Why? Especially Safari users are not necessarily using the latest version, or enterprise users might be using Firefox ESR which lags behind in features. For those, we want to use well-supported CSS features.
We can use Relative Color Syntax and modern colorspaces to achieve an (almost) identical result.
.example {
background: var(--bg);
color: lch(from var(--bg) calc((60 - l) * 1000) 0 0);
}
This computes a new color from the background color, with a different lightness. Lightness values above 60 stay positive, values below become negative; multiplying by 1000 causes them to clip the 0..100 range and CSS will interpret the value as either 0 (black) or 100 (white).
Here is a more colorful example: https://codepen.io/foobear/pen/LEbaWGB Show archive.org snapshot