Dynamic CSS – how to use PHP in your stylesheets

Q: Can you use PHP in your stylesheets?

A: yes, of course!

But why would you want to? Well, maybe you want your users to be able to control the font size or colour scheme on your site. Or maybe you need so supply and style individual IDs to dynamically generated content. Or maybe you want to change the header image depending on the time of day (like I do on this site). Whatever your reason it’s very simple to achieve.

Perhaps the most simple method would be to include the styles in question in the <head> section of your HTML and manipulate them there, something like…

<style type="text/css">

## add you PHP here...


…however, that’s a bit untidy — if you want to move ALL your CSS, static & dynamic into one stylesheet, here’s how…

1 Rename your style sheet to give it a .php extension eg: style.css → styles.php

2 This on its own will not work, you need to inform PHP that it is dealing with CSS, this is done by adding a PHP header to your stylesheet. Add the following to the top of your stylesheet.

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

From now on you can add any PHP you require to your CSS file.

3 One more thing. You need to change the reference to your css file to make sure it is linking to the PHP file, something like:

<link rel="stylesheet" type="text/css" media="screen" href="css/styles.php" />

4 Or, if you prefer, and your site is hosted on an Apache server, you could use mod_rewrite to rewrite the url to do this, you would need to create a file called .htaccess* in the root level of your site containing the following code (if it already exsists, copy and paste the code into it):

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^css/styles.css /css/styles.php [L]

this tells all calls to styles.css to access styles.php

* more on mod_rewrite & .htaccess files coming soon…