0

I was wondering if it is possible to use javascript variables inside a CSS code. I would like to implement something like this

p{
font-size: size;
}

Where, the value of the variable size would be defined by,

var size=document.getElementById("first").fontSize;

These two codes would be written in the same file and be saved as "somefile.css". This could be really useful to use in browsers which do not support or have javascript disabled.

2
  • 1
    You can use a library like jQuery for this. See api.jquery.com/prop. Commented Sep 21, 2012 at 17:50
  • @SableFoste Because, of course, jQuery is the answer to everything. And what about the "browsers which do not support [...] javascript" did you miss, exactly? Commented Sep 21, 2012 at 17:51

6 Answers 6

1

No, you can't do that, there are no variable in CSS.

But you can change your style from javascript :

var items = document.querySelectorAll('.someClass');
for (var i=0; i<items.length; i++) {items[i].style.font = "100px Arial"};​​​​​​​​

DEMO

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

Comments

0

If you want this kind of functionality you should use LESS or SASS

Comments

0

You cannot embed variables in CSS. It is not a scripting language.

IE has some proprietary support for this, but it's not part of "the spec".

Comments

0

Wait wait wait, so you're trying to implement JavaScript "to use in browsers which do not support [it]"? Have a think about what you're asking here.

What's wrong with just setting a font size? Some people use em units to scale elements in proportion to the text size.

1 Comment

Maybe what I was trying to ask was whether it was possible or realistic to design such a language which would allow us to use that functionality.
0

You might check out LESS/SASS.

http://coding.smashingmagazine.com/2011/09/09/an-introduction-to-less-and-comparison-to-sass/

Comments

0

The short answer is no. You can however do these things on the server side using php or whatever other language you like, you have to set the mime type to css at the top of the file. You will have to use a page redirect if javascript does not run.

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.