如何在 CSS 中包含 PHP 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5338972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:04:48  来源:igfitidea点击:

How to include PHP code in CSS?

phpcss

提问by Hyman Billy

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?

我有一个脚本,我需要在 CSS 样式表中包含 PHP 代码。但是当我尝试在我的 CSS 文件中添加 PHP 代码时,没有任何反应!是否可以?

回答by Your Common Sense

Rename your CSS file to end in .php,

将您的 CSS 文件重命名为以.php,

styles.css -> styles.php

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

但是,我怀疑您是否真的需要在 CSS 文件中包含 PHP 代码。

Good point from the comments below, place

下面评论的好点,地方

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

at the top of the file.

在文件的顶部。

回答by Pekka

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.

除非它有大量的动态值,否则最好有一个静态 CSS 文件,并且只覆盖那些在 PHP 已经运行的文档中动态变化的部分。它为您节省了一个请求(加上引导等所需的时间),并使大部分样式表可缓存。

In your PHP/HTML page's head section:

在您的 PHP/HTML 页面的头部部分:

<!-- 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>

回答by Myles Gray

Have you tried adding this to your .htaccess?

您是否尝试将其添加到您的.htaccess?

AddType application/x-httpd-php .css

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

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

回答by ChrisR

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 代码放在 CSS 文件中是行不通的。您必须先创建一个 PHP 文件,然后让该文件输出 CSS 代码。并设置正确的内容类型标题。

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

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