My wife called me out for looking at CSS through a pair of Programmer’s Glasses™. She hastily added this could well be a Good Thing, and I suppose I’ll just interpret it as a compliment. In fact, I must say I agree, feeling more like a “developer” than a “designer”.
Let’s first look at how we ended up at this name-calling. Here’s a code snippet from Ethan Marcotte‘s book Responsive Web Design from the A Book Apart series:
font-size: 1.5em; /* 24px / 16px */
He then goes on to state that:
I usually put the math behind my measurements in a comment to the right-hand side of the line, which makes future adjustments much, much easier for me to make.
At first glance, this makes sense. However, in the long run, this feels really weird to me: it smells like code duplication. The actual result and the calculation in the comment both express the “what“, just in different form. It reminded me of Clean Code, where a whole chapter is dedicated to comments, and I’d think this would fall under the Bad Comments section (“Noisy Comment”, perhaps?).
Now I’m currently thinking I must be wrong: everyone who is something in responsive design is generating this type of sample code. Maybe it is because I should read this kind of code like:
font-size: 1.5em; /* Form 1 */
/* font-size: (24px / 16px)em; */ /* Form 2 */
Both forms describe what the font-size should be. Form 2 is probably “best” from a Clean Code point of view (as it’s most descriptive), but unfortunately only form 1 is valid (plain) CSS. As a compromise both forms are kept.
So, what are the options for improving things? There’s at least a few I can currently see:
- Combine “Form 1 and 2”. Accept that you’ll need discipline to keep the measurement and comment in synch. This is what the Responsive Design community leaders seem to practice.
- Just use “Form 1”. You’ll loose (or never have) the benefit of understanding your measurement.
- Use a CSS pre-processor. There are Sass and LESS, the most well-known ways to introduce (among others) calculations in stylesheets.
- CSS3 modules. The CSS3 Calculations module introduces calculations, and the Variables module may even take this one step further (as far as preventing code duplication is concerned).
To be honest, this list is currently my reverse order of preference. I’d love for option 4 (the CSS3 modules) to become a success. Until then, I’m bound to investigate the CSS pre-processors, because option 1 and 2 are both crappy, in my opinion.