eco consulting

CSS constants with SSI: CSSI!  

Dave Everitt 1 September 2008, last updated 30-Oct-2008

I was thinking the other day (after working on a WordPress-based site with crazy long CSS) how good it would be to have CSS colours stored in variables that were all held 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 book group" Facebook group.

Andy Clarke replied with a link to Rachel Andrew's article on using PHP to do just this, 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 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

1. create a .cssi file with all your site's colours (say "colors.cssi"):

<!--#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.

Add a comment…

Allow up to 7 days for comments to be moderated before publication. Comments are limited to 2000 characters (around 300 words). Your email will remain confidential.

Name:
Email (optional):
Comment: