I’ve been doing a little bit of web design the last few weeks.
It appears that css style sheets do not natively support the definition of variables and the ability to perform basic addition/subtraction operations. This would be helpful when an element is resized and other page elements must be resized appropriately, or when the colour of an element is defined as a different shade of the colour of an adjacent element where a hex value can be simply added or subtracted. I find this surprising, so there is probably a very good reason for this.
A hacky but perfectly acceptable solution is to define the style sheet as a php file.
Typically the style sheet is named style.css. To do this the file will need to be named style.php unless the server is configured to parse othewr files as php (I generally don’t bother with this, I’m quite happy for people to be able to see what technology I am using).
The start of the style sheet is then as follows:
header(“Content-type: text/css; charset: UTF-8″);
# All variables go here, e.g. the width of the page:
# CSS stuff below here…
width: <?php echo $pageWidth-100; ?>px;
The header() function defines the file as a css style sheet for the browser (since the file is no longer named as a *.css file). If the basic naming convention is still being followed then it is probably a good idea to keep this statement anyway to guard against changes in the server configuration. It may also help prevent the style sheet from being blocked by some web filtering proxies that are unable to categorise the data.
When the php part of the css is parsed the expressions are evaluated and printed in the style sheet with echo commands. The units of measurement (px, em, %) are then appended to the end of the expression in the stylesheet. If the programmer wanted to be imaginative the variables could be defined as strings with the units included, and functions can be defined that strip the units from the string, typecast the string as an integer, perform the mathematical operation, append the unit and typecast the result as a string. Unless this is coded very carefully and generically the resultant code is likely to be messy, so I prefer to avoid tricks like this (although the functions can be defined in another file).
Finally, the style sheet is applied to the html document with the following declaration in the header:
<link rel=”stylesheet” type=”text/css” href=”style.php” />
If used carefully this method allows style sheets to be defined that allow for easy changes in dimension. With a little thought some additional trickery can be formulated. I will leave that for another post…