PHP Dynamic CSS

Dynamic CSS

Do you wish you could change that style sheet depending on the window size or browser type, the time of day? It’s as easy as adding PHP to your style sheet.

Say hello to style.php

We know that in order to be executed, PHP must have the file extension “.php”. By copying your style.css file to style.php you will be able to use all of the power of PHP to manage the CSS. Once this is done, you must now reset the content type to CSS by adding this line to your style.php file:

<?php

header("Content-type: text/css; charset: UTF-8");

In my example, I used a database to store the default colors of a Website. Then retrieve them and place them into variables within the “dynamic CSS” file. The very first thing I do is to make sure that there is something in those variables in case the database fails or there is a lost connection:

//set default colors here in case the db fails
$page_background_color="fff1da";$h1_color="6a2a2b";$h2_color="03413e";$h3_color="03413e";
$page_text_color="6a2a2b";$box_internal_color="99dd99";$box_border_color="03413e";$box_text_color="6a2a2b";
$box_heading_color="400000";$blocks_color="03413e";

Next, re-load those variables with database data using something like this:

include '../includes/initdatabase.php';
$query = "SELECT * FROM defaultwebsitecolors"; // get default color settings
$result = mysql_query($query);
if(!$result)
{
   echo "Unable to Execute the Query <br />".mysql_error($link);
   exit();
}
$row = mysql_fetch_array($result);
$id= $row['id'];
$page_background_color= $row['pagebackgroundcolor'];
$h1_color= $row['h1color'];
$h2_color= $row['h2color'];
$h3_color= $row['h3color'];
$page_text_color= $row['pagetextcolor'];
$box_internal_color= $row['boxinternalcolor'];
$box_border_color= $row['boxbordercolor'];
$box_text_color= $row['boxtextcolor'];
$box_heading_color= $row['boxheadingcolor'];
$blocks_color= $row['blockscolor'];
?>

At this point, all we have to do is use PHP to echo the variables into the style sheet. Here is an example of that used on a paragraph style:

p  {line-height:140%; font-weight:600;color: #<?php echo $page_text_color; ?>;}

 Say goodbye to style.php

“WHAT? You just told me to swap that extension to .php?”  The method above is probably the best, however some systems will not work without that style sheet extension “.css” intact. The next best thing to do is edit your .htaccess file so that your  original “style.css” will be searched for PHP code to execute. If you have renamed your style.css file, put it back to it’s original file name style.css. Then add this to your .htaccess file:

<FilesMatch “^.*?style.*?$”> SetHandler php5-script </FilesMatch>

Now the server thinks that you want to run PHP5 with the extensions of .css; Keep in mind, this could get very confusing if others work on the site not knowing you made these changes!