New in CSS: relative colors
- 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.
119 | 119 | 119 | 128 | 128 | 16.4 | 16.4 | 25.0 | 119 |
And if you want to laern more, head over to Jim's blog to learn more. It's a good one!
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%);
}
Join 5.5k readers and learn something new every week with Web Weekly.