Skip to main content

CSS relative colors

Relative colors in CSS

Until fairly recently, there was no way to define a CSS colour as being a derivative of another colour. It is now available, but it's fairly poorly supported at the time of writing: Chrome only started supporting it in version 119 (October 25, 2023).

A chart from caniuse.com showing compatibility as of Dec 11, 2023:

image.png

Firefox, IE and Operate don't support this feature, and neither do quite a few Android browsers. You can choose to use the new feature, but if you want to have a reasonable amount of backwards compatibility, you might want to do it the painful old fashioned way.

Defining additional RGB variables per color for defining translucent colors

It's horribly inefficient, and annoying, but outside of the new relative color syntax, the only way to manipulate colors easily where opacity is concerned is to effectively define them twice, e.g.

:root {
  --some-color: #005050;
  --some-color-rgb-value: 0, 80, 80;
}

The reason for this is that you can't use variables with hex values inside the rgb or rgba functions. If you're not planning on using any opacity, then you don't need to care about this, but without using RGB values you can't make opacity-modified versions of colours, like so:

:root {
  --some-color: #005050;
  --some-color-rgb-value: 0, 80, 80;

  /* Some other declarations... */

  --some-translucent-color: rgba(var(--some-color-rgb-value), 0.5);
}

Using var() in this way works if the value of the variable is in RGB form, but not if it's in hex form.