Dynamic variables in CSS via JavaScript

There seems to be a need for dynamic variables in css. All the solutions require some server side code … is JavaScript an option ?

I personally don't have a need for dynamic variables but I can see how it could be useful. I just never understand why JavaScript is not an option

why javascript …

  • JavaScript is widely available
  • Most people don't disable it
  • JavaScript is cached by browser
  • You can test and run locally
  • I am sure there are more?

examples

Enough talk, I did two quick examples ... these are files are identical except they set different variables for colors and size:

how

I am not going to give a tutorial on JavaScript, but just want to show the basic concept.

//variable in css
background-color: DVCJ_BGCOLOR;

//javascript setting
DVCJ_BGCOLOR    = '#fff';

//replacement
dvjc_css = dvjc_css.replace(/DVCJ_BGCOLOR/g, DVCJ_BGCOLOR);

//write css
document.write('<style>'+ dvjc_css +'</style>');  

the source

dvcj.zip

Daniel Bulli

I am a yardie (means Jamaican), and develop web type things. Excels at strategy and vision, with a keen sense of design and user interface. An avid photographer, and a frustrated golfer.

Subscribe to Daniel Bulli

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!