开发者

How to include PHP code in CSS?

开发者 https://www.devze.com 2023-02-18 13:13 出处:网络
I have a script, and I will 开发者_如何学Pythonbe needing to include PHP code in the CSS stylesheet. But when I try adding PHP code in my CSS file nothing occurs! Is it possible?Rename your CSS file t

I have a script, and I will 开发者_如何学Pythonbe needing to include PHP code in the CSS stylesheet. But when I try adding PHP code in my CSS file nothing occurs! Is it possible?


Rename your CSS file to end in .php,

styles.css -> styles.php

However, I doubt that you really need to have PHP code in a CSS file.

Good point from the comments below, place

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

at the top of the file.


Unless it's a terrible lot of dynamic values, it is much better to have a static CSS file, and override only those parts that change dynamically inside the document where PHP is running already anyway. It saves you a request (plus the time needed for bootstrapping etc.), and makes the majority of the style sheet cacheable.

In your PHP/HTML page's head section:

<!-- static resource -->
<link rel="stylesheet" href="styles.css">

<!-- Dynamic styles -->
<style type="text/css">

  body { color: <?php echo $body_color; ?>; }
  h1   { font-size: <?php echo $fontsize."px"; ?>; }
  p    { color: <?php echo $paragraph_color; ?>; }

</style>


Have you tried adding this to your .htaccess?

AddType application/x-httpd-php .css

http://www.phpro.org/articles/Embedding-PHP-In-CSS.html


Putting PHP code in a CSS file will not work. You will have to create a PHP file first, and let that output CSS code. And also set the correct content type headers.

<?php
    header('Content-type: text/css');
    $color = "#ff6600";
?>

body {
    color: <?=$color?>
}
...


You can do like this

<div class="background">
 <p style="color:#fff;">Hello World</p>
</div>

<?php
$color = '#000';
?>

<style>
.background{
    background : <?php echo $color?>;
} 
</style>
0

精彩评论

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