CSS constants/variables with SSI: CSSI!

Dave Everitt 1 September 2008, last updated (none)

After working on a WordPress-based site with crazy long CSS, I thought how good it would be to have (at least) all the CSS colours stored in variables (constants?) in a single file, so you could change every instance throughout a site, across multiple stylesheets. So I posted a message to the Transcending CSS Facebook group.
Update: if you want more than to store a few CSS variables, you can take a look at SASS, LESS or Less.js, which are designed to do this and more. SSI is still a nice simple solution, but they are implementations of the whole 'programmable CSS' thing.

Andy Clarke replied with a link to Rachel Andrew's article on using PHP and there's also Davis Walsh's CSS Variables using PHP, but PHP seemed like overkill for such a simple task, so I had a chat with my friend and co-developer Ben Daglish, who suggested using Apache's SSI (Server Side Includes). SSI means that Apache itself does the server-side processing, so no scripts are necessary. He left it with me, and the result is… it works!

Enable SSI for .cssi files

If you have control over your Apache setup, make sure SSI is enabled in your Apache config (.shtml is the usual extension) - this is covered exhaustively on the web.

Add a new Apache 'Directory' directive as below for your styles directory:

<Directory "/users/you/webite/domain/html/styles">
  AddHandler server-parsed .cssi
  Options Includes
</Directory>

'AddHandler server-parsed .cssi' tells Apache to find files ending with .cssi and process any SSI instructions they contain. We could have given them any unused extension, but .cssi indicates that they're mixture of CSS and SSI. 'Options Includes' simply allows SSI within this directory.

If you don't have control over your server setup, ask your provider to: "enable SSI in my 'styles' directory for files ending .cssi". Apache shouldn't process all .css files, so the .cssi extension enables the server to target just those using SSI in their CSS.

Create SSI-enabled CSS files: an example

1. create a .cssi file with all your site's colours (say "colors.cssi") or any other CSS that's duplicated throughout your style sheet:

<!--#set var="mybackground" value="#303" -->
<!--#set var="mycolour" value="#303" -->

2. Include "colours.cssi" into your main stylesheets (or just add the variables to the top of a single stylesheet), then echo the variables whenever you need the colours:

<!--#include file="colors.cssi" -->
body { background: <!--#echo var="mybackground" -->; }
p { color: <!--#echo var="mycolour" -->; }
.someclass {
  padding: 0.5em;
  background-color: <!--#echo var="mycolour" -->;
}

3. now you can change the colour values in colours.cssi (or at the top of your single .cssi file) and have these changes appear in all the stylesheets that use these variables.