A PHP way to simulate CSS Variables
Georges Trottier
October 16th 2014

Here, I describe a scheme using PHP to implement CSS variables. A pseudo-CSS file with the .php extension is used. It contains PHP code as well as standard CSS statements. The PHP code extracts values from a cookie and various CSS statements are set by PHP code that assign them user defined values. Its implementation is relatively simple and it prevents redundancies in the file.

Cascading Style Sheets is a presentational style sheet language. It is an amazing tool but it lacks one important functionality: it cannot contain variables whose values ​​will be evaluated when a page is loaded. Indeed, CSS variables are one of the most requested features, especially by those who are accustomed to using programming languages ​​such as PHP or Javascript.

The "CSS Working Group" (W3C) is becoming closer to defining this highly requested feature [see CSS Variables draft) but it may be not what was expected. For now, we must be content with what we have and take roundabout ways to perform the task.

It defines a custom property as property whose name starts with "var- " and contains at least one other letter. Property names that have var- as a prefix (e.g. var-name) represent custom properties, contain values that​​ can be reused throughout the document using a variable. Here, a variable is an association between an identifier and a value that can be assigned to CSS properties using the var() function notation. Another thing that the proposal mentions explicitly is setting custom properties to be read by JavaScript.

Here's an example of such a CSS file taken from A Look Into: Using CSS Variables.

var-primary-color: #333; /* declaring the main-color variable */
/* The rest of the CSS file */
html { var-primary-color: #333;} /* use of main-color variable */

However, it is a proposal, not a specification [CSS Custom Properties for Cascading Variables Module Level 1 - W3C Last Call Working Draft, 6 May 2014]. This is the way of the future but we have to wait!

I want it right now!

Suppose that you would like to use it now! First, change the extension of your CSS file from .css to .php. Since Web browsers are not that picky about file extensions when dealing with the HTML link tag, you can link to your pseudo-CSS file as follows:

<link rel="stylesheet" type="text/css" media="screen" href="/include/style.php">'

What they are picky about is the header data that it receives for that file. What that means is that you can link a *.php file with the proper header data in the place of a *.css file, and the browser will interpret the result just like standard CSS. To do so, add the PHP header that tells Apache to output the file as CSS:

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

In this context, the example cited from A Look Into: Using CSS Variables above would become:

<?php
  header("Content-type: text/css; charset: UTF-8"); 
  $primary-color='#06c'; /* declaring the main-color variable */
  /* The rest of the CSS file */
  html {primary-color:<?php echo $main-color ?>;} /* use of main-color variable */
?>

With this scheme, you can set as many pseudo-CSS variables as you want et disperse their values in the CSS code by replacing CSS numerical values of your choice by PHP statements such as <?php echo $MyVar ?>. It works!

In a previous design of this web site, I used this roundabout to CSS variables for the sake of dynamically changing display features of the pages. I wanted the users to be able to change the color theme and the font-size of the pages just by clicking on icons on the page [Dynamic cascading style sheets - internal or external? ]. At the time, I called the method "dynamic cascading style sheets" because of the user interaction. Now, I call it "simulation of CSS variables".

Demo

For this demo, I have used a dynamic change in the color theme of the page (this page only on this site) that can be performed by the client on the user interface: the banner, the menu, the title and the heading tags of the page will change color but it could also apply to the size of fonts and other features. Try it below and see what it gives:

Pick a color theme
blue   red   teal   brown   black

The PHP preudo-css file

For this demo where the client dynamically selects one of the colors, the pseudo-CSS file appears as a PHP file where the value of the color theme is set by a cookie. Depending on the value of this cookie (teal, blue, brown, red or black - its default value), the PHP variable $Colors is set to one of the colors. Assigning <?php echo $Colors ?> to the <title>, <h1>, <h2>, <h3> and <h4> tags and to the banner id property in this file avoids redundancies and sets all these CSS elements to the selected color. See the code of the pseudo-CSS file:

<?php
header("Content-type: text/css; charset: UTF-8");
if (isset($_COOKIE['theme'])) // is cookie('theme') there?
	$Theme = $_COOKIE['theme']; // set it
else $Theme = 'black';
  if ($Theme == 'teal')$Colors = '#063';
  if ($Theme == 'blue')$Colors = '#00f';
  if ($Theme == 'brown')$Colors = '#630';
  if ($Theme == 'red')$Colors = '#f00';
  if ($Theme == 'black')$Colors = '#000';
?>

#banner {
	color: #fff;
	text-align: center;
	width: 60%;
	margin: 0 auto;
	height: 200px;
	background-color:<?php echo  $Colors ?>;
	border: double 15px;
	border-radius: 50%;
	line-height: 50px;
}

.title
{
  text-align: center;
  margin-top: 1em;
  margin-bottom: 1em;
  text-decoration: underline;
  font-size: 1.6em;
  font-weight: bold;
  color: <?php echo  $Colors ?>;
}

h1 {
	color: <?php echo  $Colors ?>;
	text-align:center;
	font-size:1.5em;
	font-weight:bold;
	text-decoration:underline;
}

h2
{
	color: <?php echo  $Colors ?>;
	text-decoration:underline;
	font-size:1.3em;
}

h3 {
	color: <?php echo  $Colors ?>;
	font-size:1.2em;
	text-align:left;
	color: <?php echo  $Colors ?>;
}

h4 {
	text-align:left;
	color: <?php echo  $Colors ?>;
}
/* more statements */

As this snippet indicates, the value of the $Colors PHP variable is obtained from the "theme" cookie when the page is loaded as there are no other way to pass the value to the pseudo-CSS file.

Important!
I tried to detect the $_GET as follows in the pseudo-CSS file:
if (isset($_GET['theme']) $Theme = $_GET['theme']) else $Theme = 'black';
but it failed.

The cookie

For the demo to function correctly, a cookie must be set when the theme is changed. It is done when the user clicks on one ot the theme colors: upon reloading of the page, the theme cookie is fetched

if (isset($_GET['theme']))
		setcookie("theme", $_GET['theme'], time() + 60*60*24*30, "/");  // 30 days

and the pseudo-CSS file grabs the cookie.

Conclusion

The code developed in this article allows CSS-variable capability using a pseudo-CSS file with the .php extension. It is a first step toward CSS-variables and it is supported by all browsers.

For the demo, I have had to use a cookie to set the value of the color theme because the change originated from a selection made dynamically by the user. Because of the type of cookie that was used, the selection will survive for a month once installed on the client!

Although I have used this concept in 2009,it is not new. See

  1. Supercharge Your CSS with PHP Under the Hood publiched August 2009 by Michael Owens;
  2. Embedding PHP In CSS by Kevin Waterson; and
  3. CSS Variables with PHP published December 3, 2009 by Chris Coyier in CSS-Tricks.

References

  1. Why CSS Needs No Variables
  2. Using CSS variables
  3. CSS Custom Properties for Cascading Variables Module Level 1 - W3C Last Call Working Draft, 6 May 2014
  4. Can I use CSS variables?
  5. A Look Into: Using CSS Variables


    Questions or comments?
    E-Mail
    Last modified: October 21st 2014 22:18:46. []