且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将php变量使用到.css文件中

更新时间:2023-09-02 12:03:58

实际上可以.

第一个解决方案

使用.php代替使用.css文件扩展名

设置变量

<?php

   header("Content-type: text/css; charset: UTF-8"); //look carefully to this line

   $brandColor = "#990000";
   $linkColor  = "#555555";
?>

使用变量

#header {
   background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no-repeat;
}
a {
  color: <?php echo $linkColor; ?>;
}

...

ul#main-nav li a {
  color: <?php echo $linkColor; ?>;
}


第二种解决方案

创建一个文件并将其命名为style.php,然后在您的style.php中,如下所示在标签中设置样式

style.php

<style>
.blabla{
   ....
}

#heeeHoo{
   ...
}
</style>

然后将style.php包含到您的文件(test.php)中,例如

<html>
<head>
    <?php include 'style.php'; ?>
</head>
<body>

</body>
</html>

那是正确的答案.像内联css一样思考,但这实际上在外部文件中

I have a css file named test.css and I want to use into it of $var.$var is at test.php. test.css is attached in test.php. My structure is something like this:

//test.php

<html>
<head>
<?php $var = 'anything';?>
<link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body></body>
</html>

and this is test.css:

// test.css

.<?php echo $var> { // css property }

Currently test.css does not work. In fact, I want to knoe how can I use of a php variable as a class name into a css file ?

Actually you can.

1st Solution

Instead of using the .css file extension, use .php

Set up variables

<?php

   header("Content-type: text/css; charset: UTF-8"); //look carefully to this line

   $brandColor = "#990000";
   $linkColor  = "#555555";
?>

Use variables

#header {
   background: url("<?php echo $CDNURL; ?>/images/header-bg.png") no-repeat;
}
a {
  color: <?php echo $linkColor; ?>;
}

...

ul#main-nav li a {
  color: <?php echo $linkColor; ?>;
}


2nd and short solution

Create a file and name it like style.php, then in your style.php set your styles in tags like below

style.php

<style>
.blabla{
   ....
}

#heeeHoo{
   ...
}
</style>

then include style.php to your file (test.php) like

<html>
<head>
    <?php include 'style.php'; ?>
</head>
<body>

</body>
</html>

That is the correct answer. Think like inline css but that is actually in external file