Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Preprocessor or PHP?

If I'm writing code in PHP is there a reason why I would use a CSS Preprocessor instead of PHP? For example, I could use PHP in my CSS file by having this in my header:

<link rel="stylesheet" type="text/css" media="all" href="style.php" />

That way I could pass it variables like style.php?color=#000

Or I could use something like LESS to preprocess my CSS. If I use less.js, I'm not sure how I would be able to pass variables like in the previous example.

Now, I've heard that PHP CSS files can't be cached so I can see why that would be a problem, especially if the CSS file was large. But I'd like the ability to pass variables to my CSS sheet.

Can someone tell me a little more about why I'd use one over the other, and/or how I would pass variables to my .less file if I used less.js?

like image 924
Sam Avatar asked Jan 29 '12 18:01

Sam


2 Answers

Now, I've heard that PHP CSS files can't be cached so I can see why that would be a problem, especially if the CSS file was large.

PHP CSS files can be cached, but if you pass dynamic values to them, the point of caching is usually lost. If you have a dynamic value that may change with every request, caching becomes pointless.

Also, shoving huge amounts of mostly static CSS through the PHP preprocessor tends to be a waste of server resources.

The much easier approach is usually to have static CSS files, and to declare all dynamic values in the page body:

<!-- the static style sheet declares all the static values --> 
<link rel="stylesheet" type="text/css" href="static.css"> 
<!-- now you override all the dynamic values -->
<style>
  .classname { color: <?php echo $color; ?> }
</style>

This way, you can have dynamic values as you please, but you still avoid having a lot of CSS data being processed by PHP.

like image 171
Pekka Avatar answered Sep 26 '22 00:09

Pekka


Any and all HTTP requests CAN be cached, you just generate appropriate cache headers see rfc2616.

Interestingly, caching will work very nicely because if your GET values change then you DON'T want the PHP to be cached anyhow. So go ahead and enjoy using them.

Part of your css should be something like:

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

Here is a very interesting tutorial on it: http://css-tricks.com/snippets/php/intelligent-php-cache-control/

like image 39
Ahmed Masud Avatar answered Sep 27 '22 00:09

Ahmed Masud