Reusing color value for different transparency levels in USS

What is the Unity-recommended way to handle using the same (variable) color with different transparencies in USS? A use case is defining a style sheet with some color variables (primary, secondary, tertiary, info, success, error, etc.) in a single place and reusing it throughout a (maybe large) system of UI components with varying values of transparency.

In CSS you would do

--palette-error-rgb: 240,60,60;

.component-with-intransparent-bg {
        background-color: rgb(var(--palette-error-rgb));
}

.component-with-transparent-bg {
        background-color: rgba(var(--palette-error-rgb), 0.15);
}

According to the docs using var() within other functions is not supported by USS, so I suspect there is a different recommended approach to this.

How does this translate to USS without having to specify each transparency level as a separate variable?

1 Like

This unfortunately is a limitation of the current system. You’ll need to define every color var as a single rgba value

Thanks @uMathieu for your reply!

Is this already on the roadmap or else, is there a tracker where I could create a feature request?

1 Like

Transparency is a property outside the color itself, and it’s also known as alpha component, You can’t code transparent as pure RGB (Red-Green-Blue), but you can use the RGBA notation, in which you define the color + alpha channel together:

rgba(red, green, blue, alpha)

Where alpha defines the opacity as a number between 0.0 (fully transparent) and 1.0 (fully opaque)

color: rgba(255, 0, 0, 0.5); /* 0.5 is the transparency value */

There’s also the HEXA notation ( #RRGGBBAA ) now supported on all major browsers, which is pretty much the same as RGBA color code but using hexadecimal notation instead of decimal. It’s called HEXA ( HEX + Alpha ). It takes in 8 digits instead of 6. The last pair is Alpha. So the pattern of pairs is #RRGGBBAA. Having 4 digits also works: #RGBA.

color: #FF000080; /* red at 50% opacity */

Here the FF0000 is the color and 80 is the transparency. Where 80 is the hexadecimal equivalent of 50%.

Is there a feature request to +1?