Making Your CSS Files Dynamic With a Little PHP

I’ve grown so accustomed to writing in languages like PHP where I can use variables, loops, and arrays to cut down on the amount of duplicate code I need to create. I love the flexibility I had to make things as efficient and modular as possible. So I used to dread working with a CSS file. CSS is a huge step up from the days of inline styling, but I wanted more. If I was slightly changing the shade of green on the site, I wanted to change it in one place and have it update anywhere.

This is possible (and even easy) with a little PHP.

Here’s what the line in your header tag is going to look like:

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

Now if you treat style.css.php as a typical CSS file, it’s not quite going to work. You need a little extra bit of code at the top, to make sure the web browser treats this as css.

<? header(“Content-type: text/css”); ?>

With that in place, your in business. You can use variables just like you would in any other css document.

<? $blue = ‘#003366;’ ?>
body { background-color: <?= $blue ?>; }
h1 { color: <?= $blue ?>; }

You can also pass variables. Remember the line of code you had back in your HTML file? What if it looked like this?

<link type=”text/css” rel=”stylesheet” href=”style.css.php?theme=green” />

Now you can do some cool tricks in your CSS file:

<?
if($theme == ‘blue’) { $maincolor = ‘#003366; }
if($theme == ‘green’) { $maincolor = ‘#339966′; }
?>
body { background-color: <?= $maincolor ?>; }
h1 { color: <?= $maincolor ?>; }

Leave a Reply

Best Practices

presented by Site Potion