Change CSS-Style Color Value with JavaScript

1.6k views Asked by At

I have a box with a style that sets the color of the box to var(--box-color). This variable is defined in a separate CSS file, which I use for constants etc.:

:root{
--box-color: rgba(250,250,250,1.0);
}

I want to make the color of the box lighter using JavaScript. I could just apply a brightness filter using box.style.filter = brightness(...), but that doesn't seem very elegant, and as the box also has children that should not be affected by the dimming, it is not the way to go for me. Is there a way to change the specific color values using JavaScript, with variable initial values? Something like:

box.style.backgroundColor.r -= 10;
box.style.backgroundColor.g -= 10;
box.style.backgroundColor.b -= 10;

I could also do it with String separation, if the color would be defined by an rgba(r,g,b,a) statement, but it is defined with a variable, and I also don't know how to get the value of that variable with JS.

And if you don't understand my problem, feel free to ask in the comment section.


I'm going for a less complicated and more elegant structure now, so this question does not require an answer anymore. I'll not delete it though, in case other people come up with a similar problem.

2

There are 2 answers

2
Christian On

You can get the color value with javascript and split it into r, g, b and a colors for example like that:

let rgba = box.style.backgroundColor.match(/[\d\.]{1,3}/g);
// r === rgba[0]
// g === rgba[1]
// b === rgba[2]
// a === rgba[3]

then you can simply edit the rgba() values and convert them back to the original string:

rgba[3] -= 0.1

box.style.backgroundColor = 'rgba(' + rgba.join(',') + ')';

I just hope this can help somehow. Please tell me, if I don't understand you right.


I'm sorry for the bad Question I wrote before - I still can't write comments :(

1
macbem On

CSS Variables are seen as normal CSS properties, so you can just access them normally via element.style, e.g. document.documentElement.style['--variableName'].

Note the usage of document.documentElement as the element we use to grab the styles - you used :root to define the variable, so we have to look for the values at the root element, which in, DOM, is the document.

If you want to set the value of a CSS variable via JS, you can use document.documentElement.style.setProperty('--variableName', value).

In this case, you could just add some different CSS Variables that would store the new color value or just edit the existing one to suit your current needs.

Useful links: