CSS Variables with PHP

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

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

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

Content-type

At the top of your new style.php file set the Content-type back to CSS:

<?php
    header("Content-type: text/css; charset: UTF-8");
?>

Set up variables

Now you can set up variables for whatever you like:

<?php
    header("Content-type: text/css; charset: UTF-8");

   $brandColor = "#990000";
   $linkColor = "#555555";
   $CDNURL = "http://cdn.blahblah.net";
?>

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.

#header {
   background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no-repeat;
}
a {
  color: <?php echo $linkColor; ?>;
}

...

ul#main-nav li a {
  color: <?php echo $linkColor; ?>;
}

Extend the power / Other ideas

  • While you are at it, might as well compress the CSS with 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.

<FilesMatch "^.*?style.*?$">
SetHandler php5-script
</FilesMatch>

Carlo DeAgazio wrote in to say this works for him in WordPress:

<?php
 $absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
 $wp_load = $absolute_path[0] . 'wp-load.php';
 require_once($wp_load);

  /**
  Do stuff like connect to WP database and grab user set values
  */

  header('Content-type: text/css');
  header('Cache-control: must-revalidate');
?>