PHP variables into CSS?

Hey,

I’m trying to set some CSS values from PHP.
The way I tried doing it by defining the PHP variable in the PHP page, for example:

$bodyFont = "Arial, Helvetica, Sans-Serif";

and then in the CSS file, write it like this:

body {
font-family:<?php echo $bodyFont; ?>;
}

but it doesn’t seem to work.
Any idea how can I do it?

Thanks

That’s because CSS files don’t get parsed by PHP. You’d have to either get your server to parse .css files by PHP (which would be a waste of server resources, really) or, better, get PHP to generate all the CSS and spit it out into a file - using something like file_put_contents.

Eventually I would like to pull the values from a database.
Is it possible if I’ll be use PHP to generate the CSS?

I found this:
http://interfacelab.com/variables-in-css-via-php/

Another thing, what if I’ll change the css file extension to .php? Is it wise?

Another thing, what if I’ll change the css file extension to .php? Is it wise?

That’s the obvious simple solution which I didn’t think of! The only problem with that is that the browser is going to be downloading a fresh copy of your CSS every time instead of caching it.

Another solution is to put all the CSS that isn’t going to change in a file, and produce the PHP-generated CSS straight into <style> tags right in the HTML <head>. It’s a bit ugly, but probably best in terms of performance.

Another possibility:

<body style="font-family:<?php echo $bodyFont ?>">

Hmm forgot about the CSS cache thingy -.-

Think the best solution is really setting the dynamic CSS into the <head>

Thanks !

You can generate the css on the fly with php, and instruct the browser to cache it by using the proper http headers, but generally it’s probably not the way to go about it.

I think if you do the css right, most of the css rules will probably not need to be dynamic. Only a select few will. For that situation, use a regular external css file for the rules that don’t change, and personally I would just put the dynamic rules in an inline <style> block in the page.

It really depends on how dynamic the rules are, and how much effort you want to put into it.

The decision not to have variables in CSS is perhaps the most moronic one to come down from the W3C.

One of my side-projects is to implement less into my PHP framework, though as a module that can be dropped into any PHP framework. I have other things I have to work on first though. Less addresses the issue above and a lot more.

Moronic perhaps now, but back when it came out it might not have been the most obvious thing to implement.