Artboard 16Google Sheets iconSwift icon
Published at
Updated at
Reading time
This post is a note that includes my thoughts about something I found online. Check it out yourself!

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!👏

If you want to star and follow browser bug tickets, here we go:

Head over to Jim's blog to learn more. It's a good one!

Was this post helpful?
Yes? Cool! You might want to check out Web Weekly for more WebDev shenanigans. The last edition went out 4 days ago.

Related Topics

Related Articles