Why you should use RGB values for CSS variables

Why you should use RGB values for CSS variables

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.

Defining a RGB variable

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);

A final note on aliasing

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!