Working with CSS and PHP

How to Use Variables in Cascading Style Sheet with PHP

Working with CSS and PHP - Mark Alexander Bain
Working with CSS and PHP - Mark Alexander Bain
Cascading style sheet are a vital part of every web site, but it's not possible to define variables in them. This is unless, of course, the CSS is written in PHP

The CSS (Cascading Style Sheet) is one of the great time savers for any web site designer. Anyone using this simple technique will be able to:

  • create a consistent look and feel for a web page
  • create customized formatting
  • apply this consistent look and feel to a whole web site
  • propagate any changes to the style to the whole web site by updating a single file

And then, just to put the the icing the on the cake, a programmer can make the style sheet dynamic by using PHP. If they do that then they can:

  • use variables with CSS
  • provide customizable style sheets
  • alter the styles according to user or user role

However, before starting on the PHP it's worth noting CSS can be used on a web site.

Using a Cascading Style Provide Consistency Across a Web Site

The concept of CSS is quite simple: the styles to be used by a web page are stored in a simple text file, for example:

a, a:visited {
background-color: white;
color: #004225;
}
a:hover {
background-color: #004225;
color: white;
}

Here all anchors will:

  • be displayed with racing green text and a white background
  • change to white text with a racing green background when the mouse pointer is moved over them

If this is saved into "style.css" then it can be picked up and used by any web page that includes it in the opening document head.

Creating a PHP Based Style Sheet

Just like a standard style sheet a PHP style sheet is a simple text file. However, it must include one essential line:

header("Content-type: text/css");
?>
This ensures that the file outputs any style information in the correct format, if the file is saved as "style.php" then in can be called in the same way as any other style sheet:
And, as before, this can be used by any web page on the server. Using PHP Variables with CSS Now that the CSS is using PHP it is easy for the programmer to start to use variables to define colors rather than hard coding them:
header("Content-type: text/css");
$racinggreen = "#004225";
echo <<
a, a:visited {
color: $racinggreen;
}
a:hover {
background-color: $racinggreen;
color: white;
}
END;
?>
This means, of course, that the programmer only needs to change a color definition in one place, and that they don't have to worry about updating multiple references. Not only does the programmer only have to updated a single file, but they also only have to update a single line in that file.

Mark Alexander Bain - Mark Alexander Bain is a writer, Mo Bro and consultant for all aspects of software development at dsquared. He has also written regularly ...

rss
Advertisement
Advertisement
Advertisement