CSS Variables With PHP


Normally you define your CSS in a file, let's call it style.css, that looks something like the code below.


div.small{
font-size:12pt;
color:#F3F3F3;
}
div.medium{
font-size:18pt;
color:#F3F3F3;
}
div.large{
font-size:24pt;
color:#F3F3F3;
}


Then in your HTML files, you would inclde the style sheet with the following code in the header of the file.


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


In style.css above, notice that div.small, div.medium, and div.large all have the same color. It might be nice to have a variable for the color. Therefore, if we wanted to change the color of all three divs we would only have to make a change in one place instead of three. To do this we create a PHP file called style.php. Below is the code for style.php.


<?php
$color="#F3F3F3"
?>

<style type="text/css">
div.small{
font-size:12pt;
color:<?php echo $color?>;
}
div.medium{
font-size:18pt;
color:<?php echo $color?>;
}
div.large{
font-size:24pt;
color:<?php echo $color?>;
}

</style>


Finally in your HTML files, you would inclde style.php instead of style.css with the following code in the header of the file.


<head>
<?php include 'style.php'; ?>
</head>

Copyright 2010 Paul Foley. All rights reserved.