开发者

How to write css classes in php file?

I am creating some dynamic template and I have an issue that I开发者_运维知识库 want to use PHP variables in external CSS file.

Example: if stylesheet is styles.css and then I want to use this file as styles.php so that I can use variables in this file to make css dynamic.

What should I do for this. Thanks in advance.


  1. Rename file to styles.php (or configure server to run PHP interpreter in CSS files).
  2. Send appropriate Content-Type header:

    header('Content-Type: text/css');
    
  3. Write your code:

    <?php
    
    header('Content-Type: text/css');
    
    $a = '#123456';
    $b = '#654321';
    
    ?>
    
    body > a {
        color: <?php echo $a ?>;
    }
    


Use an .htaccess file and the following line:

AddType application/x-httpd-php .css

This will make your server parse .css files as if they were .php.


The problem with making dynamically generated CSS files is that they won't be cached. You'll be forcing to user to hit your server at least twice: once for the php output, and once for the css.

If you're only making a few minor parts of the CSS dynamic, consider creating a regular standard CSS file with suitable defaults in it, and then having your PHP pages output a suitable <style> block which issues the overrides. That way your main CSS file can be cached, and you get dynamic styles at the cost of a few lines of extra output in your PHP file.


I know this is old but @MarcB is incorrect on caching

Here is a cachable version of the php CSS

<?php
  ob_start ("ob_gzhandler");
  header("Content-type: text/css; charset: UTF-8");
  header("Cache-Control: must-revalidate");
  $offset = 60 * 60 ;
  $ExpStr = "Expires: " .
  gmdate("D, d M Y H:i:s",
  time() + $offset) . " GMT";
  header($ExpStr);
  $blue="#00f";
  $red="#f00";
  $green="#0f0";
 ?>
  #div{
   color:<?=$blue?>;
   background:<?=$red?>
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜