How to Convert HEX to OKLab
Converting a hexadecimal color to OKLab moves your color from the legacy sRGB color space into a modern, highly optimized perceptual color space. Introduced to CSS more recently, OKLab is designed to fix the mathematical quirks and perceptual bugs found in older spaces like CIELAB.
What is OKLab?
Created in 2020 by Björn Ottosson, OKLab is a perceptual color space. Like CIELAB, it uses three axes:
- L: Perceived lightness (from 0 to 1).
- a: How green or red the color is.
- b: How blue or yellow the color is.
However, OKLab uses a completely different mathematical foundation based on LMS (Long, Medium, Short) cone responses in the human eye. This makes it significantly better at predicting how humans actually see color transitions.
Why Use OKLab Over HEX?
If you interpolate (create a gradient or animation) between a blue and a white HEX code, the middle of the gradient will often look slightly purple. This is a known flaw in how RGB math works. Even CIELAB struggles with blue hues, often shifting them toward purple during transitions.
OKLab was specifically engineered to fix this. Gradients generated in OKLab space are flawless. Hues stay perfectly stable as they transition to white or black, making it the absolute best color space for image processing, CSS gradients, and color mixing.
The Conversion Math
Converting HEX to OKLab requires matrix multiplication. The HEX code is converted to RGB, and the gamma curve is removed to create linear light. This linear RGB is multiplied against a specific 3x3 matrix to convert it into LMS cone space. A non-linear cube-root function is applied to simulate human eye response, and a final matrix multiplication yields the L, a, and b values.