Published at
Updated at
Reading time
2min

Do you remember the good old Sass days? Using Sass, you could manipulate colors with helper functions such as darken or lighten. This wasn't possible in pure CSS, but now it's on its way!

Jim Nielsen's post Dynamic Color Manipulation with CSS Relative Colors explains how the new relative color syntax enables flexible color manipulations. Relative CSS colors are super new and only available in Safari Tech Preview (and even in Tech Preview, you have to toggle a development flag).

So be warned, the following is future music!

The new relative color syntax (Relative color specification) comes with a new from keyword.

.something {
  --color: #4488dd;
  /* transform a color value into `rgb` */
  background-color: rgb(from var(--color) r g b / .5);
}

Using from you can "destruct" color values into their rbg, hsl or lch components. And the best thing: from works for color definitions such as green, #445599 or rgb(100 200 0). You can soon transform hex values into rgb and hsl and back!

But how could you implement a darken function then? Pair things with calc. 🤯

.something {
  --color: red;
  /* transform `red` to `hsl` and manipulate its lightness */
  background: hsl(from var(--color) h s calc(l - 20%));
}

Transform a color value into a format that's easy to manipulate and call it a day!

I'm amazed by this CSS addition, and it shows that smart people write the specs. Developers asked for lighten, darken and various other CSS functions in the past, and we now got a solution that can do this but much more. Beautiful!👏

And here's the current browser support.

MDN Compat Data (source)
Browser support info for Relative `color()` syntax
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
11911911912812818Non25.0119

And if you want to laern more, head over to Jim's blog to learn more. It's a good one!

CSS Relative color examples und use cases

Find some examples on how to use relative colors below.

Relative colors can be used to create entire color palettes.

.wheel {
  --base: #dd55aa;
  --swatch1: hsl(from var(--base) h s 0%);
  --swatch2: hsl(from var(--base) h s 20%);
  --swatch3: hsl(from var(--base) h s 40%);
  --swatch4: hsl(from var(--base) h s 60%);
  --swatch5: hsl(from var(--base) h s 80%);
  --swatch6: hsl(from var(--base) h s 100%);
}
If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles