I have a script, and I will be 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?
5 Answers
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.
1 Comment
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>
1 Comment
Have you tried adding this to your .htaccess?
AddType application/x-httpd-php .css
Comments
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>