Alpha Value in CSS Color Properties
07 February 2023
Today1, I learned that that you could use a
/ alpha value in CSS color property functions (
It looks like this:
color: hsl(0 0% 0% / 0.5); color: rgb(0 0 0 / 0.5);
alpha value is a number between
0 (full opacity) and
1 (no opacity).
Previously, you had to use a function variant to change the alpha:3
color: hsla(0, 0%, 0%, 0.5); color: rgba(0, 0, 0, 0.5);
a at the end of each function, ie.
This is really handy, because you can change the content of the function without changing the function name itself. Which is more practical when using React and CSS-in-JS libraries. I know I would have use that a few times already if I was aware of this small spec change.
The support is pretty good (more than 92%), so it's mostly safe to use on modern websites.
It's not really new anymore, but I don't code that much nowadays. That was a small nice surprise. ;)↩
I (and others) still recommend to use the↩
hslfunction instead of
rgbor hex values. It's more powerful and as soon as you grasp how the model works, it's easier and quicker to manipulate. Especially for variables and theming purposes.
The old notation still works, but it's considered legacy.
The commas are also optional now (and considered legacy as well).
AND there is another syntax using commas and an alpha value (
hsl(0, 0%, 0%, 0.5)/
hsla(0, 0%, 0%, 0.5)) or an alpha percentage (
hsl(0, 0%, 0%, 50%)/
hsla(0, 0%, 0%, 50%)).
Basically, you can do anything you want, but using the↩
/ alphasyntax without commas and
asuffix in the function name is the proper and preferred way. 🥴