Dynamic style sheets using PHP

20 September 2009

Sometimes you may have the need to create a style sheet using values from within a datebase table, or you may need to pass variables into the style sheet.

To do this you will need to create a dynamic style sheet.

A few uses of a dynamic style sheet would be:

  • Within a CMS where the user can pick their own colours
  • When you have different areas within your website all with different colour schemes
  • When your website has accessibility functionality that allows the website user to change font sizes

And any other reason when it's easier to just have the one dynamic style sheet, rather than writing multiple style sheets and selecting teh correct one depending on user selection or area of the website being viewed.

To create a dynamic css style sheet you will need to have your style sheet as a php file, so for now we'll call this "style.php".

On any page that uses the style sheet you will need the following as normal (but remember it's .php not .css)

<link rel="stylesheet" type="text/css" href="/css/style.php" />

Or if you wanted to pass a variable into the dynamic style sheet, like a colour scheme for that page you'd do something like:

<link rel="stylesheet" type="text/css" href="/css/style.php?colour_scheme=<?php echo $colour_scheme; ?>" />

On the dynamic style sheet (style.php) the first few lines have to be

header("Content-type: text/css");

This basically tells the web browser to render this file as a css style sheet.

On the dynamic style sheet you can just add your styles as usual, until you want something dynamic at which stage you'd need to call it using php. Here's an example using the colour_scheme variable we used above.

if ($_REQUEST['colour_scheme'] == "blue")
echo "color:#0000ff;";
echo "color:#ff0000;";


Please leave a comment using the form provided.