Saturday, December 10, 2005

Using CSS constants with PHP

I ran across an article the other day using my favorite Web 2.0 app that described how to use constants in CSS with PHP. The author's method I felt was a bit overly complicated however since it required the use of an additional file that would essentially replace the embeded PHP variables with their respective values. I think there is a much easier way to do this which I will demonstrate.

** file: mycss.php **
<? $mycolor = "blue"; ?>

.myclass {
font-size: 12pt;
color: <? echo $mycolor ?>
}
** file: index.php **
<html>
<head>
<link rel="stylesheet" href="mycss.php" type="text/css">
<body>
<span class="myclass">Hello world!</span>
</body>
</html>
This works because PHP is interpreting the CSS file as if it were PHP code. After it interprets it, what is left is CSS code and thanks to the type directive in the link tag, that is how it is rendered by the browser. Hence, no need for an additional file that does a massive search and replace. An online example can be found at my site.

The next challenge for me is to get something like this working in Ruby on Rails.

No comments: