OKLCH()
I was at the State Of The Browser event recently, which was great as always.
Manu gave a great talk about colour in CSS. A lot of it focused on OKLCH. I was already convinced of the benefits of this colour space after seeing a terrific talk by Anton Lovchikov a while back.
After Manu’s talk, someone mentioned that even though OKLCH is well supported in browsers now, it’s a shame that it isn’t (yet) in design tools like Figma. So designers are still handing over mock-ups with hex values.
I get the frustration, but in my experience it’s not that big a deal in practice. Here’s why: oklch()
isn’t just a way of defining colours with lightness, chroma, and hue in CSS. It’s also a function. You can use the magical from
keyword in this function to convert hex colours to l, c, and h:
--page-colour: oklch(from #49498D l c h);
So even if you’re being handed hex colour values, you can still use OKLCH in your CSS. Once you’re doing that, you can use all of the good stuff that comes with having those three values separated out—something that was theoretically possible with hsl
, but problematic in practice.
Let’s say you want to encode something into your CSS like this: “if the user has specified that they prefer higher contrast, the background colour should be four times darker.”
@media (prefers-contrast: more) {
--page-colour: oklch(from #49498D calc(l / 4) c h);
}
It’s really handy that you can use calc()
within oklch()
—functions within functions. And I haven’t even touched on the color-mix()
function.
Hmmm …y’know, this is starting to sound an awful lot like functional programming:
Functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that map values to other values.