| Dynamic CSS using PHP |
|
|
|
| Written by Raymond Fain | |
| Friday, 03 August 2007 | |
|
PHP has been known to generate a lot of dynamic output including HTML, images, PDF files, and certainly CSS. Dynamic CSS can be very logical to use because it can open up a lot of doors in how you scale your projects. Many sites will have CSS files ranging from a couple hundred to over ten thousand lines of coding. Yes this seems quite a lot but if you think about all the different content some sites have and what they do, you would not be surpised to see so much CSS used. In combination to both good CSS coding and good techniques you can ultimately spend less time working with one PHP file containing all your CSS over many different files. In this tutorial I will demonstrate dynamic CSS using Brandon's Matching Div Colums. To start off just open up two new PHP documents in your favorite editor and save as each in order: index.html, dyn_css.php. Copy paste this into your index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <body> Nunc dignissim viverra nulla. Nunc accumsan orci et neque. Pellentesque scelerisque dapibus dolor. Praesent lacus. Phasellus eu sapien ac risus consequat rhoncus. Aliquam mi urna, eleifend.
There is nothing in there you have not seen before but notice the <link> tag including the PHP file instead of a CSS file. Here it will complete the CSS portion to be used with the rest of the site. Now Copy Paste this into dyn_css.php:
<?php /* Dynamic CSS */ header("Content-Type: text/css"); if(isset($_GET['page'])){ $page = $_GET['page']; switch ($page){ case "index": $css .= '#container {'; $css .= 'background: url(../images/stories/CSS_tutorials/mct_left_col.gif) repeat-y;'; $css .= 'border: 1px #000000 solid;'; $css .= 'width: 600px;}'; $css .= '#left_col { float:left; width: 25%;}'; $css .= '#right_col { float:right; width: 75%;}'; $css .= '#content { padding:4px;}'; $css .= '.clr { clear:both;}'; break; } } else { // insert default css here if $_GET['page'] is not there } ?>
Looking at this file, you notice there is nothing before the <?php tag and after the ?> ending tag. This is because it is a strict PHP file that will only output CSS. Header() function will give the rest of this script the characterists of a CSS file and will be treated like one. As you can see I added in a variable that can be retrieved by $_GET which will dictate what CSS coding will be displayed according to what $_GET value has been acquired. With dynamic CSS using PHP you can really get creative and integrate this with a MySQL database or other useful functions. - Raymond Fain |
|
| Last Updated ( Tuesday, 07 August 2007 ) |



