How to include PHP code in CSS?

前端 未结 4 1714
清酒与你
清酒与你 2020-12-09 06:47

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?

相关标签:
4条回答
  • 2020-12-09 07:07

    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?>
    }
    ...
    
    0 讨论(0)
  • 2020-12-09 07:08

    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>
    
    0 讨论(0)
  • 2020-12-09 07:10

    Have you tried adding this to your .htaccess?

    AddType application/x-httpd-php .css
    

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

    0 讨论(0)
  • 2020-12-09 07:12

    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.

    0 讨论(0)
提交回复
热议问题