5

Can we set calculated result as a background color in CSS.

background-color: var(--backColor) + #101010;

here --backColor is a CSS variable.

Gopinath
  • 55
  • 1
  • 5

1 Answers1

3

Without using a pre-compiler or a JavaScript/jQuery solution, you're going to be really limited.

As far as I have researched, I don't think this will be possible with HEX values, unless you find a way to splice the hex value, into 3 different values and then convert them to their decimal relative.

However, this solution is not for hex, but for those looking for an rgb/rgba solution you could split the value into their own respective variables, and then use calc() to add/subtract/multiply as decided.

If you read the specs here, you will see that the browser handles min/maxing for you where a value exceeds 255 or below 0, making it easy to insert erroneous values without worrying about logic.

Values outside the device gamut should be clipped or mapped into the gamut when the gamut is known: the red, green, and blue values must be changed to fall within the range supported by the device.

Now, I can't say this is cross browser compatible, but testing in latest versions of Chrome, Edge produce quality results. However, Chrome didn't seem to have an upper/lower limit for clipping, with the limited testing I did, however Edge does have an upper limit of adding 214748 to the number. So with everything concerning compatibility, make sure you test for your needs.

Here is an example, note that you don't have to use integers, you can use percentages or any qualified combination of numbers, like combining hsl.

:root {
  --r : 0;
  --g : 0;
  --b : 0;
}
#div {
  /* value should be aqua:  0, 255, 255 */
  background: rgb(calc(var(--r) * 255), calc(var(--g) + 1 * 255), calc(var(--b) + 255));
}
#div2 {
  /* value should be red: 255, 0, 0 */
  background: rgb(calc(var(--r) + 500), calc(var(--g) * 500), calc(var(--b) - 500));
}
<div id="div">
  Div
</div>
<div id="div2">
  Div 2 With Min/Max clipping
</div>
soulshined
  • 9,612
  • 5
  • 44
  • 79