Skip to content

Instantly share code, notes, and snippets.

@pachacamac
Last active April 20, 2016 17:39
Show Gist options
  • Save pachacamac/0d5be8b465c0ebc0fe51c13f8605f5f3 to your computer and use it in GitHub Desktop.
Save pachacamac/0d5be8b465c0ebc0fe51c13f8605f5f3 to your computer and use it in GitHub Desktop.
Simple Sass like variables in CSS through JavaScript. Obviously not a good idea for production but if you're just hacking a bit locally, why not?
<style class='vcss'>
/*
$container-width: 1280px;
$main-font: 1rem 'Dosis', sans-serif;
$light: #fdfdfd;
$dark: #222;
*/
@import url("http://fonts.googleapis.com/css?family=Dosis");
body { background-color: $light; color: $dark; font: $main-font; }
.container { position: relative; text-align: left; width: $container-width; max-width: 90%; margin: 0 auto; }
</style>
<script>
(function(){
var vars = {}, css = document.querySelectorAll('style.vcss');
function vreplace(s){ for(var k in vars){ s=s.replace(new RegExp('\\$'+k+'(?!:)(?!-)\\b', 'gm'), vars[k])}; return s; }
for(var i=0; i<css.length; i++){
css[i].textContent.replace(/^\s*\$(\w[\w\-\d]+):\s+(.*?);\s*(:?$|\/\/)/igm, function(m,k,v){ vars[k] = v; } );
for(var k in vars){ vars[k] = vreplace(vars[k]); css[i].textContent = vreplace(css[i].textContent); }
}
})();
</script>
@pachacamac
Copy link
Author

Now also handles variables in variables, as long as they're defined in the right order. I.e.:

$foo = Hello;
$bar = $foo world;

.container{ content: '$bar'; } /* is now 'Hello world' */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment