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?

  • Gonzalo

    What about the overhead?

  • http://ilovecolors.com.ar Elio

    Great article, the most interesting web-related tutorial I’ve seen in a while.

  • http://clustrmedia.us clustrmedia

    I can remember setting up a dynamic stylesheet using php on a very large, very public, convention and visitors authority website about 5 years ago. I was fresh out of college and it was the first big project of my career. At the time it was a fantastic solution because the website used different color schemes for different sections of the site. Would I do it that way again? Not a chance.

    I think for most situations you would be better off looking to a Object Oriented CSS solution. The problem with a dynamic stylesheet (beyond performance issues for large sites) is that most designers will freak out if they see php in the css. As was the case on that site I worked on.

  • http://freewarematter.blogspot.com FreewareMatter

    Cool! If you make CSS files cached with PHP, this will be awesome!

  • pratfall

    A classic example of DOING IT WRONG.

    Designers design in view files.
    Programmers program in controller files.

    With the above configuration, every CSS file sent out by the server passes through the PHP parser. Instead of sending out a flat file, you’re adding database calls and program instructions.

    Your use cases- random themes, different themes for different times of day, or better use cases like user preferences, can all be accomplished (and, in any reasonable-quality web framework, are accomplished) by including multiple CSS files, chosen by a single database call.

    This is an ugly hack, and a n00b mistake.

  • http://fearlessflyer.com michael soriano

    I always wondered what styles.php were used for. This comes very handy. Good article.

  • Tice

    I work with php-css on my cms for a year now. It is the only way I found to give the user the option to change (or better fine tune) the appearance of the website. Using a simple include/explode in the style.php for a file with a var-string with the colors, fonts, sizes, etc. is maybe an even simpler way to integrate that.

  • http://arbent.net Angie Bowen

    Very interesting article that seems to have sparked some just as interesting conversation. I’d love to see more from both sides of this.

  • http://puddletowndesign.com Portland Web Design

    I think serving CSS with a php extention is a bit of mistake. Like another commenter suggested, you are adding overhead to each page call. Also, I’m not 100% sure, but I don’t think browsers will cache a php file the same way as they will a CSS file.

    There are some interesting alternatives to this like HAML/SASS.

  • devsmt

    ther’s nothing wrong with code generation, but requires strong comunication skills to lead your co-workers

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources » Shai Perednik.com

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources « Graphic Art Source

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources | Theme Center

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources | Gacik Design Blog

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources « Alanalanya's Blog

  • Pingback: 50+ Fresh CSS Techniques, Tutorials and Resources