8

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 5

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you do this, make sure to send the correct Content-Type header.
17

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

This was such a simple solution and my 2 day headache is finally gone! Thank you!
4

Have you tried adding this to your .htaccess?

AddType application/x-httpd-php .css

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

Comments

2

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?>
}
...

Comments

-1

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>

1 Comment

How it's different from the answer directly above?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.