Constants for CSS

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:

<?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 :)

5 Comments

  1. Joe Lencioni 13 years ago

    Great idea, but you might want to check out CSS Crush. It lets you define and use variables in your CSS files in addition to a lot of other neat things.

  2. Author
    Dave Seah 13 years ago

    Joe: That is really cool! Updating my notebook :)

    • Joe Lencioni 13 years ago

      No problem. There are other similar things out there that might be worth checking out, like Sass, LESS (PHP version), Compass. I haven’t personally used any of these (including CSS Crush), so I can’t really recommend one over another.

  3. Author
    Dave Seah 13 years ago

    I looked into LESS and SASS earlier; they seemed more cumbersome to implement than I had patience for last night :)

  4. J Wynia 13 years ago

    For years before tools like LESS and SASS came around, I just used PHP/ASP.NET/Python/whatever on the server side to generate CSS and get variables, etc. in my CSS. I’ve been doing that for so long that when LESS/SASS showed up, it kind of surprised me that more people hadn’t already “had variables” in their CSS for years.

    I still use my server-side templating language for generating my CSS instead of one of the newfangled tools, but that’s largely because I keep color codes, font sizes, etc. in settings in database storage for use not only on the site itself but on reports, PDF exports, etc.