Trick Out Your CSS With Server Side Code

June 16, 2009 • By

CSS is a great tool for styling web pages and keeping the style code in it’s own place, instead of mucking up the HTML. Unfortunately, CSS is not a programming language, and does not have the tools that come with a server side language like PHP. However, we can use Server-side languages to generate style sheets, and get the best of both worlds!

Without further delay, here are a few PHP tips on how to trick out your CSS.

Setting Up a Style.php File

Creating a style.php is going to require a little bit more set-up than creating a regular CSS file. First, open up your root .htaccess file, and copy and paste this line into it:

AddType application/x-httpd-php .css 

(note: this may not be necessary for all servers, but it never hurts to be safe)

Now create a new file and name it style.php . At the top of your file, include this line of code(this MUST be the very first line of the document):

<?php Header ("Content-type: text/css");?> 

This ensures that the browser knows to parse this as a CSS file, not an HTML file.
You can now write CSS just like you would in a regular CSS file, and you can include PHP code the same way you would in a regular PHP file. Keep in mind that the PHP will be ‘writing’ the style sheet in the same manner that it writes HTML, so use the echo or print commands anytime you want to write something to the stylesheet.

Using Variables

One of the simplest and most useful features of using server-side scripting with CSS is the ability to use variables. Once you have a color palette for your site, you can save all of the color codes as variables, like so:

  $darkGray = “#333333”;
  $offWhite  =  “#F7F7F7”;
  $skyBlue   =  “#B9EBED “;
  $lightBrown = “#A65D29”;
  $darkBrown    =  “#704A2E “;

Now, whenever you want to use one of these colors, you can call the variable, like so:

.contentBlock {background-color:<?=$darkBrown;?>; border: 2px solid <?=$lightBrown;?>;}

This has several advantages. First of all, if you ever need to change one of the colors, you can change it in one place, instead of several. This also makes writing code quicker and simpler, since you don’t have to constantly cut and paste hex codes. This also makes the file more readable, as it is easier to tell what color something is looking at $skyBlue instead of #B9EBED.

Generate Palettes With PHP

Now let’s try something a little trickier: creating a set of classes that cover a range of colors. We’ll take our dark brown and dark gray colors, and generate 10 classes, with each one containing a color that falls in between the two.
To begin, we will need to write two functions. One will convert a hex code into an array of RGB values, and the other will be able to convert an array of RGB values into a hex code.

Here the first function, which will handle both 3 digit and 6 digit hex codes:

function HexToRGB($hex){
  $hex = ereg_replace("#", "", $hex);
  $color = array();

 if(strlen($hex) == 3) {
  $color['red'] = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
  $color['green'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
  $color['blue'] = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1) );
 else if(strlen($hex) == 6) {
  $color['red'] = hexdec(substr($hex, 0, 2));
  $color['green'] = hexdec(substr($hex, 2, 2));
  $color['blue'] = hexdec(substr($hex, 4, 2));
  return false;

  return $color;

And here is the second:

function RGBToHex($colorArray) {
  $hex = "#";
  $hex.= dechex($colorArray['red']);
  $hex.= dechex($colorArray['green']);
  $hex.= dechex($colorArray['blue']);
  return $hex;

These are what we call helper functions. These functions will be used in the next function we write, which will be a gradient creator. It will take three arguments: the hex code of the first and second colors, and the number of colors you want to find between them:

function GradientCreator($firstColor, $secondColor, $numOfColors){
  $firstRGB  = HexToRGB($firstColor);
  $secondRGB = HexToRGB($secondColor);

  //calculate the difference in each of the colors:
  $redDiff = ($firstRGB['red'] - $secondRGB['red'])/$numOfColors;
  $greenDiff = ($firstRGB['green'] - $secondRGB['green'])/$numOfColors;
  $blueDiff   = ($firstRGB['blue'] - $secondRGB['blue'])/$numOfColors;

  //iternate for the number of colors, create the hex codes in between:
  $output = array();
  for($i = 0; $i < $numOfColors; $i++){
    $redAdjust = $redDiff * $i ;
    $greenAdjust = $greenDiff * $i ;
    $blueAdjust   =  $blueDiff  * $i ;

    //build the new color in an RGB array format
    $newColor = array();
    $newColor['red'] = $firstRGB['red'] - $redAdjust;
    $newColor['green'] = $firstRGB['green'] - $greenAdjust;
    $newColor['blue']   = $firstRGB['blue'] - $blueAdjust;

    //add it to the output array
    $output[$i]  = RGBToHex($newColor);
  return $output;

now we have an array of a range of colors we can use throughout our stylesheet. Here’s an example of how we can use them:

<?php $brownToGray  =  GradientCreator($darkBrown,$darkGray,10); ?>
.gradient0 {background-color:<?=$brownToGray[0];?>;}

you could even loop through the array to generate a bunch of classes quickly:

  foreach($brownToGray as $index => $color){
    echo “.gradient$index {background-color: $color;}n”;

we would then have 10 classes we can use wherever. here’s what they would like if you applied one of each to li elements in a ul:

Get Styles From a Database

Another advantage of using PHP in your stylesheet is that you can store and retrieve values from a database. In this example, we will be using this for a theme system for user profiles. Let’s assume we have a database table called UserThemes with the Following variables:


When calling the stylesheet, pass the User_ID variable to it as a get variable, so your stylesheet link should look something like this:

<link rel='stylesheet' href='style.php?User_ID=<?=$User_ID;?>' type='text/css' media='screen' />

We can then query the database to get these variables when the page is loaded, and set variables appropriately:

  $query = “SELECT * FROM UserThemes WHERE User_ID = '{$_GET['User_ID']}'”;
  $result = mysql_query($query);
  while($row = mysql_fetch_assoc($result)){
    $MainColor = $row['MainColor'];
    $SecondaryColor = $row['SecondaryColor'];
    $AccentColor = $row['AccentColor'];

We can now use these variables in the stylesheet, and allow each user to have a unique look for their profile!

Other Uses

The list of things you can do by combining PHP and CSS is nearly endless. Some people have used dynamic style sheets to have random themes, or to have different themes for day and night, or for weekends and holidays. What other uses can you think of for combining PHP & CSS?