Using variables in CSS simplifies website development and maintenance. Consider the case of color management. Defining your color scheme as variables used throughout your stylesheet will facilitate minor color tweaks or major color refreshes. You can even use variables to manage spacial relationships relative to font size (without the headache of managing em based inheritances).
CSS does not directly facilitate variables. To include variables in your stylesheet, you can overlay a server-side scripting language (such as PHP).
First, you will need to define your stylesheet as a PHP document. Rather than naming your stylesheet style.css, name it style.php. You can then include this stylesheet in the normal fashion:
<link rel="stylesheet" type="text/css" media="screen" href="/style.php" />
Most browsers assume file names ending in .php indicate HTML output. Consequently we must add a bit of code to the top of your stylesheet to announce CSS output. On the first line of your style.php file, enter:
<?php header("Content-type: text/css"); ?>
Now declare your variables:
<?php
// color scheme
$mainBG = "#2e0303"; //burgandy
$contentBG = "#f3e7ca"; //cream
$textColor = "#333"; //dark gray
$fontSize = 16;
$lineHeight = 1.25*$fontSize; //20px
?>
These variables are now available for use throughout your stylesheet. I prefer to use shorthand PHP for inline use to increase code readability. (Since I control the server on which the stylesheet resides, and the file is not intended for general distribution, longhand is optional). Your stylesheet may include statements like these:
body {
background-color: <?= $mainBG ?>;
font-size: <?= $fontSize ?>px;
line-height: <?= $lineHeight ?>px;
}
#content {
width: <?= 33*$fontSize ?>px;
margin: <?= 2*$lineHeight ?>px auto;
border: 1px solid <?= $textColor ?>;
padding: <?= $lineHeight-1 ?>px;
//remove border width
color: <?= $textColor ?>;
background-color: <?= $mainBG ?>;
}
Do you want to adjust the font size but maintain typographic balance? Change one variable. Your client called and wants the text to be a little darker? Now your matching border will not be forgotten in the update. Use of variables in CSS is easy and worthwhile.


