Variables in your CSS via PHP

Penned 16 years ago. It will take about 5:35 to read.
It was 40°F in Nicholasville, KY and the sky was clear.

There are a number of ways to use PHP with other web languages and technologies.  I myself use PHP in some of my JS scripts and sometimes even in CSS files.

While surfing the net I found someone asking for a way to create 'color variables'.  I commented outlining a way that this could be accomplished using PHP, but it was of coure garbled since I was using < and > in my comment.

Thankfully Bish found a tutorial on the net that said basically the same thing, but I thought I would write a little something up here as well, covering creating 'color constants' in your CSS, and more interesting, creating randomly generated paths for the backgrounds of DIV's.

PHP and CSS sitting in a tree

It is really a no-brainer to want to take some common CSS elements and simplify the process of changing them or updating them.  Before we get any further though, let me stress that this is a limitied use technique.  The very nature of CSS is to cascade, which would be defeated by this if you went nuts with it.

So lets take a very simple example; we want to define the base color scheme and font families we want to use for body, h1 and our menu.  Lets move those into PHP so that we can update them all with one small change.

First we begin with a bit of code that forces our PHP to conduct itself as though it were CSS:

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

Now that we have sent our PHP undercover as CSS we need to write some code to handle our fonts and colors.  And here is where we get into new territory for Sillyness.  We will be writing Object Oriented Code for this tutorial.

There are many reasons for this, the least of which would be that having a font object and a color object just makes sense when you think about it.

OOPing is the new black

The basic building block of OOP is the class.  In the simplest terms a class contains both variables and functions (which we should be familiar with by now), and serves as the template from which to spawn specific (and multiple) instances of that class.

Instances of a class are what we call 'objects'; each object you 'spawn' is a kingdom unto itself working within the confines of the variables and functions that are defined in the class.

So lets go through the steps needed to make an object beginning with a look at PHP 4 syntax:

// first we create our font class
class font {
// now lets create our CONSTRUCTOR function
function font($args=array()) {
    $this->fields = array('headline','body','menu');
     foreach ($this->fields as $field) {
            $this->{"$field"} = $args["$field"];

Okay, so lets talk about what the above code is actually doing.  First we create a class, in this case font and then we create a function called a 'constructor' and as I am sure you can already guess it allows us to construct the array that we will be populating our objects with.

So now, lets take a closer look at our constructor function.  As you can see it contains an array that will hold our font information.  You pass information to the function in an array as well, we then set the fields in the array equal to the arguments passed to our constructor with a foreach loop.  All pretty straightforward.

We would build the color class in the same way.  There is a pretty large difference between PHP 4 and 5 when it comes to writing constructors.  In 4 the class and constructor must share the same name, in PHP 5 you actually call the constructor... CONSTRUCTOR!  Scary I know:

// first we create our font class
class font {
// now lets create our CONSTRUCTOR function
 function __construct($args=array()) {
     $this->fields = array('headline','body','menu');
      foreach ($this->fields as $field) {
            $this->{"$field"} = $args["$field"];

With me so far?  If not, there is an excellent walk through of OOP from Zend Technologies... it mentions bears, how great is that?

An object lesson

My gawd I am witty.  So now it is time to create our font object.  Fortunately this couldn't be easier:

$font = new font(
          headline => "Trebuchet MS, san-serif",
          body => "Times New Roman, serif",
          menu => "Arial, Heveltica, san-serif",

Very, very straightforward here people.  We are saying that $font is a new instance (or object) of the font class, then we are creating an array that will be passed back to the font class via the constructor.  Basically we are saying set the class array equal to the arguments array.

Okay now we have a font object that contains the fonts we want to use, we need to call those fonts out in the appropriate places:

font-family: body; ?>;

h1 { font-family: <?php echo $font->headline; ?>; }

.menu { font-family: <?php echo $font->menu; ?>; }

And that is all there is to it.  We call for the appropriate 'field' from our class, which has been set equal to the corresponding argument from our object.

Randomness, my favorite

So now that we have done a little OOPing, what say we write a function that will allow us to randomly select the background of a DIV?

So the basic gist of this is that we have a DIV, lets say .header and we want it to have a different background image each time we refresh our site.  Since we have already set up our PHP file to parse as CSS, this is a breeze:

function rotater() {
    for ($i=0; $i  1; $i++) {
    $random = (rand()%6);
    $file = 'header';
    $image = $path . $file . $random . '.png';
    echo $image;

Okay so lets take the above code apart; first we are setting a variable ($path) equal to the path to our images directory, pretty straightforward.  We are then using rand() to generate a random number, in this case between 0 and 6 (hence the rand()%6)).

Next we define the $file variable, and set it to header; we then put them all together to get $image which should be randomly generated each refresh.

We then call the rotater() function from our CSS and viola, we have a randomly chosen background image for our header div:

    background-image: url() no-repeat;

Well I think that is all for now, I hope you all have enjoyed this bit o' nonsense as much as I have.  You can find the code from this tutorial over here (you will notice that I moved most of the PHP into its own file that I then included into style.php) and you can see a working copy right here.  Go ahead and refresh the page a couple of times and watch the image path change.

Further Reading

When in Doubt, Buff it Out.

Thanks for checking out the site, be sure to come back for more.