PHP Variables in your CSS

8/13/2010 9:00 AM By

Now, while there are solutions to supercharge CSS (SASS, LESS), you can use just plain old PHP to spice up your CSS powers, and there’s no need to learn any more syntax or install anything additional to preprocess your styles.

Of course, you can’t just start tossing PHP into your CSS willy-nilly; we need to do some preparation first. Depending on your server configuration, one of these methods will work for you.

  1. Change the .css extension to .php, and then at the top of your CSS file, set the content-type back to CSS with this:
    <?php header("Content-type: text/css; charset: UTF-8"); ?>
  2. Include this in your .htaccess file (changing the “style” bit to whatever your stylesheet is named):
    <FilesMatch "^.*?style.*?$">
        SetHandler php5-script
    </FilesMatch>

The first method seems to work fine on a static page, but WordPress seems to take issue with that, so using the second one (as-is, since WordPress requires a theme’s stylesheet to be named style.css) will do the trick.

Now we can take advantage of CSS variables, and even conditional statements, to fill in our styles. So let’s set up some variables:

<?php
    $imageURL = 'http://images.domain.com/';
    $link_color = '#eee';
    $alt_link_color = '#000';
?>

And of course, lets use said variables:

#logo {
    background: url("<?php echo $imageURL; ?>/header/logo.png") no-repeat;
}

a {
    color: <?php echo $link_color; ?>;
}

…

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

And of course, conditionals. If we were using WordPress, for example, we could do something like this:

<?php
    if (is_page('sunrise')) $sun_position = 'sunrise.png';
    else $sun_position = 'sunset.png';
?>

#background {
    background: url("<?php echo $imageURL; ?>/header/<?php $sun_position; ?>") no-repeat;
}

Using PHP to generate random numbers, or utilizing some of the date/time functions to change backgrounds to reflect the time of day, the possibilities are quite powerful! So go forth, and enjoy PHP-ifying your CSS.

Tags:

Comments are closed.