Constants for CSS

CSS doesn’t have constants or calculation capabilities. After looking at more comprehensive solutions (LESS and SASS), I just made a simple PHP5 template that does a couple clever things to keep things nice and tidy in one file. Here’s a simple example:

// Basic Typographic Dimensions: 

$basefontSize   = 12;
$gridSize       = 18;

$substitutions = array(
    '@timestamp'    =>    date('Y-m-d h:i:s'),
    '@basefont'     =>    $basefontSize . 'px',
    '@grid'         =>    $gridSize . 'px',
    '@basecolor'    =>    '#444'

/** DO SUBSTITUTIONS *******************************/
$fp = fopen(__FILE__,'r');
$output = stream_get_contents($fp);
foreach ($substitutions as $key=>$value) 
    $output = str_replace("[$key]",$value,$output);
header("Content-type: text/css");
print $output; 
/** BEGIN CSS ** GENERATED OUTPUT ** [@timestamp] **/

body {
    font-size: [@basefont];
    line-spacing: [@grid];
    color: [@basecolor];

/* keep adding CSS here */

Free at last!!! Basically, define the constants up top, and write your normal CSS rules syntax at the bottom, and include the PHP file as you would normally include any stylesheet.

More detail (with downloadable ZIP) over on the Code Sub-blog. This is part of the baseline grid typography experiment I have going on; it uses this templated approach to compute the various font sizes, margins, and line spacing CSS rules.

UPDATE: Adding list of other solutions, too, that do more than my hack-up :)