Using variables in CSS style sheets

By | 12th July 2011

One advantage of CSS is that your styles can be kept in a separate file from the pages that use them. This is simply a text file that ends with the .css suffix such as style.css. The suffix tells the server to treat the contents of the file as CSS. Unfortunately, the CSS standard doesn’t allow for variables within a .css file. The solution is to use a PHP file, such as style.php and include code to let the server know that the contents of the file should be treated as CSS. This can be accomplished by including the following line of PHP at the top of the style sheet;

Your style definitions can then follow so that the top of your style.php document looks something like this:

a:link { text-decoration : none; color : #FF0000; }
a:active { text-decoration : underline; color : #FF0000; }
a:visited { text-decoration : none; color : #FF0000; }
a:hover { text-decoration : underline; color : #660000; }

Your .php style sheet will now function exactly like a .css one. We’ll get to the variables in a minute but first…

Linking to your .php style sheet

You can link to your .php style sheet exactly as you would a regular style sheet. Here’s the code I placed in the section of my webpage:

Using variables in your style.php file

The advantage of a PHP style sheet is that it allows you to define variables and then use those variables throughout your style sheet. So, for the example I gave above where the a:link, a:active and a:visited styles all use the same color (#3366cc), we could define a “$linkColor” variable (The “$” before linkColor simply indicates it is a variable.) and use it in all three styles. The variable definition would look like this:

Remember all PHP code must be contained within a php tag which opens with “

We can now insert the variable into our css code like this:

Notice the opening and closing php tags.

So the beginning of our CSS file now looks like this:

a:link { text-decoration : none; color : ; }
a:active { text-decoration : underline; color : ; }
a:visited { text-decoration : none; color : ; }
a:hover { text-decoration : underline; color : #000021; }

Now to change the color of the a:link, a:active and a:visited links from red (#FF0000) to blue (#0000FF) we need only change the definition of $linkColor:

Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *