Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

27 Aug 2006

Dynamic CSS with PHP

Both html and css are simply text. Thus you should be able to generate css as easily as html with php. Now if you add a reference to the css.php file in your html (eg: ) you’ll probably experience that your browser ignores the file. How is this possible? Here is an example of a simple css.php file

body {
background-color: <?php echo 'yellow'; ?>;
}

Here is a simulation of what your browser recieves when it requests the file:

Where did that content-type header come from? Well, php outputs a default content-type header (text/html) when you don’t set value explicitely. This means that your browser will try to interpret the file as html instead of css. Although it may seem weird, this behaviour is explicitely defined in RFC 2616.

So the solution is pretty simple: explicitely generate content-type header. Here is an example for css: (You’re smart enough to figure it out for csv, m3u, …)

<?php header('Content-type: text/css');?>


body {
background-color: <?php echo 'white'; ?>


}