Ew… you got CSS in my Javascript

Andy Peterson ·

The other weekend I test drove a little Javascript library to output CSS style rules from within Javascript. I took the most obvious Javascript-literal approach to get the most out of Javascript support in editors. I called it Csster (“sister”), and it looks like:
Csster.style({
h1: { fontSize: 18, color: 'chartreuse' }
});

All it does is insert the rule into the DOM so that H1 elements are, well, chartreuse. There wasn’t initially much code behind this, but I thought it might be useful. It’s pretty much the same as jQuery’s css function, but writes out a rule instead of immediately applying it to all the elements.

I immediately added nesting of rules, similar to how SASS lets you dry-up your stylesheets. Then, with a little help from Alex, I added basic color conversions and functions like “darken” and “saturate”(demo here). I then added support for macros, so you could mix-in behaviors like rounded corners, drop shadows, and of course the ubiquitous (and awkwardly named) “clearfix”. My last pass was to make sure there are reasonable extension points for other developers. Now you can write concise and expressive CSS right along with your Javascript.

Since it’s POJS (Plain Old Javascript), it is a compact language. There’s was no need for me to write math or looping or logic functions, since Javascript’s already got them (unlike SASS). DSLs are the hottest things these days, but even the not-so-forgiving syntax of Javascript works pretty well in this case.

Why would you want to use this? Well, I thought that was the big question, but everyone I show it to has an answer. For me, I am writing pages that generate lots of their HTML markup anyway, so it is awkward to keep a separate CSS file in sync (and drag it down from the server). It works well to write self-contained jQuery plugins, as I sketched out here. I started using on a new initiative (that I can’t share yet) of my latest project, and it made prototyping and initial build-out much faster. It also makes using sprites painless– all our subtitles are in one sprite and I simply add a has: subtitle("Emotion") as one of the attributes and it works. (Previously I’d written some Ruby code to generate a CSS. Ughh.)

Please, give it a spin, and file bugs or send me comments on github.

What can we help you with?

Tell us a bit about your project, or just shoot us an email.

Interested in a Career at Carbon Five? Check out our job openings.