0

If I set something in linked JavaScript to be a variable:

color1 = green;

Can I then later call the variable in CSS, like so?

div {
  color : color1
}
3
  • Until CSS actually properly supports variables...no.
    – Paulie_D
    Feb 16, 2016 at 13:19
  • The closest you're going to get to what you're asking at the moment (regarding variables) is to use a CSS pre-processing language such as SASS or LESS: http://sass-lang.com/ Feb 16, 2016 at 13:21
  • You need to learn JavaScript and CSS before you try to combine the two. Also, your question is incomprehensible, please rephrase. Feb 16, 2016 at 13:22

3 Answers 3

3

No, not this way. However if you are interested in using varibales in CSS, you may want to learn LESS, SASS or another CSS preprocessor.

4
  • Why not also mention SASS? You are recommending a specific tool. This is biased. Try to offer all CSS preprocessors to give OP research options. Feb 16, 2016 at 13:25
  • @Mr.Polywhirl, yeah, go ahead, list all of them :). Hopefully you do not think LESS and SASS are the only ones (even though they are the most popular).
    – Anton
    Feb 16, 2016 at 14:02
  • No, I know there are others, but they are indeed the most popular. Feb 16, 2016 at 16:55
  • @Mr.Polywhirl, true, ok, I have updated my answer. Thx for comment.
    – Anton
    Feb 16, 2016 at 18:34
0

Example:

<h1 style="color:red;" id="red"> I am red </h1>
<script> //JS

document.getElementById("red").setAttribute("style", "color:green;");
</style>

In the above example, JS code selects the element h1 using id and changes it's color to green. So JS is actually altering the inline CSS attribute.

0

No. CSS can not access Javascript variables.

To use your variable in this way you would assign it to your elements style property using Javascript. It may look something like this for a single element:

var color1 = 'green',
    el = document.getElementById('myDiv')

el.style.color = color1;
<div id="myDiv">Hello</div>

Or this for a number of elements:

var color1 = 'green',
    els = document.querySelectorAll('.changeColour')

for (var i = 0; i < els.length; i++) {
    els[i].style.color = color1;
}
<div class="changeColour">Hello</div>
<div class="changeColour">Hello</div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.