Thursday, September 1, 2011

CSS Variables Using PHP

CSS is an amazing formatting tool but it has one glaring omission: variables. In My CSS Wishlist, I proposed a PHP-like syntax for CSS variables. Using PHP, I've made the idea of easy, dynamic CSS a reality.

The Sample CSS

/* globals */
*   { margin:0; padding:0; }
body { color:$body_text_color;font-size:$body_font_size; }
 
The above is a sample css file that we've named "default.css". For those that don't know PHP, any string that begins with $ is a variable.

The PHP



/* get the stylesheet */
$stylesheet = @is_file($_GET['stylesheet']) && strtolower(substr(strrchr($file_name,'.'),1)) == 'css' ? $_GET['stylesheet'] : 'default.css';
  
/* set the header information */
//will be output as css
header('Content-type: text/css');
//set an expiration date
$days_to_cache = 10;
header('Expires: '.gmdate('D, d M Y H:i:s',time() + (60 * 60 * 24 * $days_to_cache)).' GMT');

/* set the dynamic information */
//default css variable information
$default = array(
  'body_font_size' => '16px',
  'body_text_color' => '#00f'
);

//red css variable information
$red = array(
  'body_font_size' => '10px',
  'body_text_color' => '#f00'
);

/* extract the propery array's information */
extract($_GET['theme'] && ${$_GET['theme']} ? ${$_GET['theme']} : $default);

/* load in the stylesheet */
$content = preg_replace('/\$([\w]+)/e','$0',@file_get_contents($stylesheet));

/* spit it out */
echo $content;
 
There's a fair amount going on in the PHP above:
  1. We check to see if a specific stylesheet is has been asked for. If not, we'll use a default stylesheet template. In this case, the default template is "default.css". We also check to make sure that the requested file is a ".css" file and that it file actually exists.
  2. We set the header information, including: the content type, which is "text/css", and an expiration date, which isn't required but recommended for caching purposes.
  3. We set keys and values of the variables we will use in our stylesheet theme. These key => values are stored in arrays so that we may have different themes. Above we have a "default" theme and a "red" theme. Note the differences in font size and text color.
  4. We check to see if a specific theme has been asked for. If not, we use the $default theme. If the requested them doesn't exist, we serve the default theme.
  5. We read in the file content and replace any string beginning with "$" with the value specified in the PHP file's theme.
  6. We echo the output. Done.

The Usage

<link rel="stylesheet" type="text/css" href="/stylesheet.php">

The Result

/* globals */
*    { margin:0; padding:0; }
body    { color:#00f; font-size:16px; }

No comments:

Post a Comment