Dynamic CSS with PHP
Have you ever wondered if you can use PHP within your CSS file to generate definitions dynamically? Simply, all you need to do is create your style sheet with a .php extension rather than a .css extension. Then include this at the top of the file:
Now, you can use PHP to generate your style definitions.
For example, suppose you have a presentation image that you are displaying as a background image in a div container. How would you display this image if you did not know the height and width in advance? Here is one example which displays divs with random background images, having the appropriate dimensions:
<?php
$someImage[]='http://sitehatchery.com/images/header_logo2.gif';
$someImage[]='http://sitehatchery.com/images/egg.gif';
$someImage[]='http://sitehatchery.com/images/spanish-flag2.jpg';
$someImage[]='http://sitehatchery.com/images/cake.jpg';
$someImage[]='http://sitehatchery.com/images/snowboarder.gif';
shuffle($someImage);
$size=getimagesize($someImage[0]); ?>
div.someImage{width:<?php echo $size[0]; ?>px; height:<?php echo $size[1]; ?>px; background-image:url('<?php echo $someImage[0]; ?>'); }
Just refresh the screen (F5) and you'll see that the image below changes:
You could use a similar method to randomly display a combination of properties for a given element. For example:
$style['header']=array(
"background-image:url('images/logo1.jpg'); height:314px; background-color:#FFEFB1;",
"background-image:url('images/logo2.jpg'); height:124px; background-color:black;",
"background-image:url('images/logo3.jpg'); height:90px; background-color:white;",
);
$count=count($style['header'])-1;
$sel=rand(0, $count);
div.header{ <?php echo $style['header'][$sel]; ?> }
Unfortunately, the attached style sheet will not take any inputs external to the script, such as from an external class or a global variable.