Dynamic CSS with PHP - Environment Aware Style Sheets
(Page 3 of 4 )
More than once I've run into situations where I wish style sheets supported simple arithmetic. Suppose I want my style sheet to set the height of a text div 100 pixels less than the viewport's height because of some graphical banner on the page. If I know I have a window of a specific size, I could do the math and hardcode the numbers by hand. However, that isn't always the case.
Previously I would have scrounged the web searching for some JavaScript code to detect the viewport's height and then made my modifications to readjust the element's properties once the page has loaded:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html> <head> <title>Sample HTML</title> <link rel="stylesheet" href="styles.css" type="text/css" /> <script language="JavaScript" type="text/javascript"> <!-- function sizeAdjustment() { var myHeight = 0;
if (typeof(window.innerHeight) == "number") /* Non-IE */ myHeight = window.innerHeight; else if (document.documentElement && document.documentElement.clientHeight) /* IE */ myHeight = document.documentElement.clientHeight;
document.getElementById('body').style.height = (myHeight - 100 + "px"); } //--> </script> </head> <body onload="sizeAdjustment(); return true;"> ... </body> </html> |
The resize of the body object degrades nicely in some browsers but causes serious display issues in others.
Instead, I could detect the browser's viewing area and append the values to the URL when calling the style sheet.
<html> <head> <title>Sample HTML</title> <link rel="stylesheet" href="styles.css" type="text/css" /> <script language="JavaScript" type="text/javascript"> <!-- var myHeight = 0;
if (typeof(window.innerHeight) == 'number') /* Non-IE */ myHeight = window.innerHeight; else if (document.documentElement && document.documentElement.clientHeight) /* IE */ myHeight = document.documentElement.clientHeight;
myHeight = myHeight - 100;
document.write('<link rel="stylesheet" ', 'type="text/css" href="styles-css.php?height=', myHeight, '" />'); //--> </script> </head> <body> ... </body> </html> |
The JavaScript calculates the height and constructs a link to the style sheet that passes along the value. The style sheet can read the incoming values and adjust itself before being sent to the browser.
<?php header("Content-Type: text/css"); echo "body {height: $_GET[height]; }"; ?> |
Ingenious... but definitely an ugly hack. Still though it illustrates how JavaScript can communicate back to PHP on the server and how PHP can tailor a unique style sheet to fit a given situation.
Next: Conclusion >>
More Miscellaneous Articles
More By bluephoenix