How to include PHP code in CSS?

I have a script, and I will need to include the PHP code in the CSS stylesheet. But when I try to add PHP code to my CSS file, nothing happens! Is it possible?

+7
source share
4 answers

Rename your CSS file to the end of .php ,

 styles.css -> styles.php 

However, I doubt that you really need the PHP code in the CSS file.

Good point from the comments below, put

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

at the top of the file.

+17
source

If this is not a scary amount of dynamic values, it is much better to have a static CSS file and redefine only those parts that dynamically change inside the document, where PHP already works anyway. It saves the request (plus the time it takes to boot, etc.), and makes most of the stylesheet available.

In the header section of the PHP / HTML page:

 <!-- 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> 
+10
source

Have you tried adding this to your .htaccess ?

 AddType application/x-httpd-php .css 

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

+4
source

Inserting PHP code into a CSS file will not work. First you will need to create a PHP file and allow this to output CSS code. Also set the correct content type headers.

 <?php header('Content-type: text/css'); $color = "#ff6600"; ?> body { color: <?=$color?> } ... 
+2
source

All Articles