3

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.

2
  • 1
    What css preprocessor are you using? Commented Jan 8, 2018 at 15:33
  • you can't. Sorry Commented Jan 8, 2018 at 15:35

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess you missed a link
Did you forget to add link? Also, link only answer is not a good way to answer any question. Do provide the code snippet and description of what it does.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.