Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing css variable in JS file

Tags:

css

angular

I am having a CSS file which has some variable define

 @red: red-color
 @yello: yellow-color
 ....

I can use this variable in CSS file, But I want to know how can I access them in my JS file.

like image 324
Sunil Hiray Avatar asked Mar 18 '26 01:03

Sunil Hiray


2 Answers

Assuming you're using native CSS variables and not some preprocessor, take a look at this page. At the bottom there's a section called Values in JavaScript which describes how to access native CSS vars in JS code.

getComputedStyle(element).getPropertyValue("--my-var");

However if you are using a CSS preprocessor, it is not possible to retrieve the variables via JS since they're already processed in the build process.

like image 94
Niels de Bruin Avatar answered Mar 20 '26 17:03

Niels de Bruin


Those are not CSS variables, but LESS variables (as they start with "@")

Those get compiled into simple, static property declarations, so no way to change them at runtime (other than addressing every property).

IF you use proper CSS variables (aka CSS Custom Properties) you can easily access them with javascript at runtime and chage it with the style.setProperty method.

But they are not widely (enough) supported, so make sure to include a fallabck.

like image 20
Facundo Corradini Avatar answered Mar 20 '26 17:03

Facundo Corradini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!