user4920811
user4920811

Reputation:

how can I use of a php variable into a .css file

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 ?

Upvotes: 7

Views: 35430

Answers (2)

hakki
hakki

Reputation: 6501

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

Upvotes: 15

bnahin
bnahin

Reputation: 816

You can use <style> in the PHP file.

//test.php

<html>
<head>
<?php $var = 'anything';?>
</head>
<body>
<style>
<?php echo $var; ?>
</style>
</body>
</html>

The style can also be put in the <head>.

Upvotes: 0

Related Questions