In my “Different Degrees of Custom Property Usage” article, I noted a situation about colors and CSS custom properties where I went “too far” with breaking up HSL color values. Breaking every single color into its H, S, and L parts is may be a step too far.
But you probably do want to split it up like this:
html { --color-1-hsl: 200deg 15% 73%; --color-1: hsl(var(--color-1-hsl));
}
So, two custom properties per color in your color system. Why? Because now you’ve got a really easy way to use it and you’ve got a way to apply alpha to the color if you want.
.card { background: var(--color-1);
}
.card-with-alpha { background: hsl(var(--color-1) / 0.5);
}
There’s not really any other way to take an existing color in CSS and apply alpha transparency to it. Well, I say that, but actually…
/* Future CSS! (works in Safari TP right now) */
.card-with-alpha { background: hsl(from var(--color-1) h s l / 0.5);
}
That’s neat, but I’m not entirely sure when we’ll be able to rely on that in production.
You know what else we can’t use for anything super important in production? Houdini paint worklets. No Firefox or Safari yet on those.
A bummer, because Dave almost had this thing cracked! The insight here is that Houdini paint worklets basically return an image that you paint with <canvas>
APIs. You can paint a rectangle in Canvas with any color format, then set the globalAlpha
, return that as an image, and so that basically unlocks alpha on any color format! It works (in Chrome):
Dave chucked the code on GitHub and blogged it. Of course, it made a good video as well:
But if you need a system like this on production, just do the custom properties technique I listed first.
A previous version of this post was tweetbombed, but I’m blogging it here because real bloggers blog.
The post Color Alpha Anywhere appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.