CSS Variables and why you’re doing it wrong December 5th, 2009
I’m a great fan of the quote to the right. It’s completely true that making something bigger and more complex can be accomplished by any old fool. But making that something smaller, more compact and generally speaking more refined—well now, we’re talking about a completely different kettle of fish.
Which is why I can’t browse the Internets these days without stumbling into some new fang-dangled state-of-the-art CSS-parsing-framework Web 2.0 (beta). And every time I see them I cringe. And to be honest they’re normally written in Ruby. Which answers a hell’uva lot of questions.
Why it’s a bad thing
It’s not a bad thing per-se, but it’s a silly idea. Not the idea of CSS variables—that’s somewhat sensible. But the idea that you need some kind of framework which reads your code into memory (I call it code, because it definitely isn’t CSS), parses it and spits back CSS you could have written quicker, more readable and at a smaller file size. Not to mention you actually need all that processing power. Not much if your site gets 5 hits a day, but serving hundreds or thousands of simultaneous users as Centation’s projects tend to do and it becomes stupid. That’s what I call crazy, and that’s why I cringe.
“Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius — and a lot of courage — to move in the opposite direction.” ~ Albert Einstein
Okay, okay, okay. So it’s a bit redundant, a bit pointless and just making things more complicated—such as introducing bugs into your code for no reason. But is there a better, more simpler way of doing this? Of course. Just parse the CSS file as PHP (or your choice of programming language) and set the page headers to text/css. Add a bit of caching and the Job’s done. First of all just tell Apache to parse CSS files as PHP by adding this to your .htaccess file:
AddType application/x-httpd-php .css
Then all you need to do is make your CSS file, the barebones being:
<?php // Header information header("Content-type: text/css"); // Send file as CSS header("Pragma: public"); // Allow browser to cache header("Expires: " . gmdate("D, d M Y H:i:s", time() + 900) . " GMT"); // 15 minute life header("Cache-Control: max-age=900, must-revalidate"); // Refresh after 15 minute // Your variables $primaryColour = '#FFF'; $secondaryColour = '#000'; ?> body{background:<?=$primaryColour?>} .h1, h2, p{color:<?=$secondaryColour?>}


Comments so far
Be the first to leave a comment!