Warning: Missing argument 1 for skf\dao_kb::__construct() in /home/kevin/www/phpro.org/html/application/lib/objects/dao_kb.class.php on line 18 Notice: Undefined variable: db_connection in /home/kevin/www/phpro.org/html/application/lib/objects/dao_kb.class.php on line 19 Embedding PHP In CSS


Embedding PHP In CSS

Embedding PHP In CSS

Perhaps one of the most frustrating aspects of using PHP with websites, is getting variables into CSS. Having variables stored in an ini file, config file or even a database can make the updating of the look and feel of a site simple, however, CSS files, by default, do not parse PHP. Of course, the web server could be told to parse CSS as PHP in the same way it does for HTML.

AddType application/x-httpd-php .css

With the addition of the above line in httpd.conf or in a .htaccess, the web server will now parse PHP code that is within the CSS files. This is one solution, but a better method may be at hand.

A html file may also include a PHP file, in the same manner as it includes a CSS file. This means the stylesheet can be renamed from style.css to style.php. When included from within the head of the HTML document, the link will look like this.

<link rel="stylesheet" href="style.php" media="screen">

With the link to the style.php file in place, the PHP within the stylesheet is just a normal PHP file.

/*** set the content type header ***/
header("Content-type: text/css");

/** set the paragraph color ***/
$para_color '#0000ff';

/*** set the heading size ***/
$heading_size '2em';

/*** set the heading color ***/
$heading_color '#c0c0c0';

        color: <?php echo $para_color;  ?>;
        font-weight: bold;
        font-size: 1.2em;
        text-align: left;

        color: <?php echo $heading_color?>;
        font-size = <?php echo $heading_size?>;
        text-align: centre;

The PHP code within the style sheet is embedded just as it would be when using HTML and PHP together in a any php file. Each of the variables are declared at the top of the script, and the values then used where appropriate. Of course, the variables could be stored in a config file or database to make changes to the styles easy from remote locations.

The code above will produce a Cascading Style Sheet as follows:

	color: #0000ff;
	font-weight: bold;
	font-size: 1.2em;
	text-align: left;

	color: #c0c0c0;
	font-size = 2em;
	text-align: centre;

An addition to CSS is pending that will permit the use of CSS variables, however, this does not exclude the of PHP to get a variable into the CSS file itself. The proposed CSS variables would look like this, and allow the defining of a variable in a @variable at-rule and then be able to use that variable through-out the style sheet.

<style type="text/css">
@variables {
  LogoBGColor: #e0e0e0;

div.logoContainer {
  background-color: var(LogoBGColor);
  color: red;


<h1 class="heading">CSS Variables</h1>
<div class="logoContainer">
This is some Text