Constants for CSS

From the 2011 Archives Computers 5 Comments

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:

<?php 
// 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');
fseek($fp,__COMPILER_HALT_OFFSET__);
$output = stream_get_contents($fp);
foreach ($substitutions as $key=>$value) 
$output = str_replace("[$key]",$value,$output);
header("Content-type: text/css");
print $output; 
__halt_compiler();
/** 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 :)