Defining CSS constants using PHP

Posted on December 23rd, 2005 by dandavis

I stumbled upon this article (article has sinced been archived here) about using PHP to define constants in CSS. I bookmarked it and finally got back to reading it this morning. I don't really have a huge need for doing this, but I have had to hack enough CSS to change color schemes that I wish that this was used in more places!

Go take a glance at this guy's article, but there is an easier way to implement constants than Tyler has shown… of course, there may be a method to his madness that escapes me.

Here's how I did it…

1. Rename your CSS file(s) as PHP: mv style.css style.php

2. Edit your style.php file thusly:

<?php
header('content-type:text/css');
include('css_constants.php');
print <<<END
// Original CSS code here
END;
?>

3. Go through your original CSS and replace common styles and colors with variables. Define those variables in css_constants.php.

css_constants.php:
$background_color = '#cca';

4. Now you go back through style.php and substitute $background_color where originally you had #caa.

style.php:
#nav {
background:$background_color
}

If I can find the time, I'll finish up my own conversions and post links to the source. Maybe. We'll see. However, if any of this really matters to you, you'll have it figured out and implemented before I get a round toit.

Post a comment