Skip to content

Instantly share code, notes, and snippets.

@parshap
Last active August 29, 2015 14:16
Show Gist options
  • Save parshap/c02ec10aa7171dc1aa42 to your computer and use it in GitHub Desktop.
Save parshap/c02ec10aa7171dc1aa42 to your computer and use it in GitHub Desktop.
CSS in JavaScript

CSS in JavaScript

Expressing styles in JavaScript isn't all that different than expressing them in css.

Plain Ol' HTML & CSS

Imagine you had the following css and html:

Styles
.foobar {
  color: red;
  font-size: 4rem;
}
DOM
<i class="foobar" />

Or using React:

React.createElement("i", {
  className: "foobar",
});

JavaScript

Now, expressing the same styles using JavaScript:

Styles
.foobar {
  color: red;
  font-size: 4rem;
}

becomes

var foobar = {
  "color": "red",
  "font-size": "4rem",
};
DOM
React.createElement("i", {
  className: "foobar",
});

becomes

React.createElement("i", {
  style: foobar,
});

And you get the power of JavaScript to boot!

Not React

What if you don't want to use React? It's not too different. You just need a way to "compile" JavaScript styles into style attributes.

Here's an example using mustache.

Mustache.render("<i style="{{style}}" />", {
  style: stringifyStyle(foobar):
});

Or you could generate classes.

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