When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.
Style.php
Instead of using the .css file extension, use .php
Theoretically you could pull the user agent and attempt to do browser-specific CSS, but that is littered with problems and not recommended.
Pull the date/time, and perhaps change some stuff on your site for the different seasons or time of day.
Generate a random number, test the result, use it to set a random background image on your header.
Not working?
I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.
CSS Variables with PHP
When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.
Style.php
Instead of using the .css file extension, use .php
Content-type
At the top of your new style.php file set the Content-type back to CSS:
Set up variables
Now you can set up variables for whatever you like:
Use variables
Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.
Extend the power / Other ideas
Not working?
I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.
I keep a personal blog too: http://chriscoyier.net