Why you should use RGB values for CSS variables

A Web Developer based in Belgium, specialized in PHP & JS development
Search for a command to run...

A Web Developer based in Belgium, specialized in PHP & JS development
No comments yet. Be the first to comment.
I recently needed to collect all changes in one file for reporting purposes. Found this article: https://ratfactor.com/cards/git-diff-with-new-files In case you need something similar on Windows, here

Some projects start with a grand plan. Others start because you just need to read a file without thinking too much about it. That was the case for spread-compat. I needed a common interface for CSV, X

With modern css, you can almost get rid of sass. But there is one last pain point : media queries. Not being able to use variables or an easy, common syntax for typical breakpoints is really annoying. That is, until you meet Media Queries Level 5. I’...

This is a quick article to share this demo I just made. https://codepen.io/lekoalabe/pen/JoPNWpX

Modals are typical UI elements for many web apps. There are countless packages dedicated to that specific features, each framework creating its own variation. Popular frameworks like Bootstrap also have custom code to deal with it. But all this feels...

While I'm a big fan of SASS variables, I tend to use more and more CSS variables since they get very good browser support. One issue I was often facing is: how to get a shade of a given color.
In SASS, this is pretty easy since you have tons of color manipulation functions. But in the browser, we only have the rgba function, that expects 4 parameters: the three rgb values and the opacity.
You might think it would be as easy as:
--color-rgb: rgb(13, 110, 253);
But you would wrong! While it would indeed define a valid CSS color, it won't be usable as such with the rgba function.
The proper alternative (as used for instance in Bootstrap 5.1) is this:
--color-rgb: 13, 110, 253;
--color: rgb(var(--color));
After that, using rgba it's as easy as:
box-shadow: 0 0 0 0.2rem rgba(var(--color-rgb), 0.25);
Here is one bonus topic. I'm working on a web component at the moment and I'd like to inherit some of the base bootstrap variables if defined. It goes like this.
my-component {
--color-rgb: var(--bs-primary-rgb, 13, 110, 253);
--color: rgb(var(--color-rgb));
--white: var(--bs-white, #fff);
button {
background-color: var(--white);
color: var(--color);
}
}
One of the good side of this approach is that it allows me to only define CSS variables at the top of my component and omit fallback values everywhere else. It keeps things nice and tidy.
Happy coding!