Menu

1 / 3

Generating a Tailwind color scale from one hex with OKLCH (in about 80 lines of JS)

DEV Community: css·Phong Đoàn·about 5 hours ago
#TNXL9pf3
#devtocss#devto#dev#const#math
Long article (2890 words) — no AI summary yet.
Reading 0:00
15s threshold

I keep running into the same problem. A project has one brand color, say #4f46e5 , and the design needs eleven shades (50 to 950) that feel like Tailwind's built-in palettes. The obvious fix is to take the hex into HSL and step the lightness up and down. It doesn't work well. HSL lightness isn't perceptual, so the results are uneven. Some steps look washed out, others look muddy, and the hue seems to wander.

I ended up writing this with OKLCH instead, and it turned out to be short. Below is a simplified version of the code I use. You can paste it into Node or a browser console and it will run.

Why OKLCH

OKLCH is the polar form of OKLab, a color space built so that numeric distances roughly match perceived differences. It has three channels:

L is perceptual lightness, from 0 (black) to 1 (white).

C is chroma, which is how colorful the color is. 0 is gray.

H is hue, an angle from 0 to 360.

The reason this matters is that HSL's "50% lightness" means very different things for different hues.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.