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.
- Rename file to
styles.php
(or configure server to run PHP interpreter in CSS files). Send appropriate
Content-Type
header:header('Content-Type: text/css');
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?>
}
精彩评论