[web-tips > CSS variable via PHP]

CSS-PHP Variable

The question has been asked numerous times in the css forum, if there is a way to use a variable from inside css and the answer has always been "No".

Well... technically, if you are using just css, then that answer is correct. However, with just a minor amount of php code (6 lines) you can use variables in css.

Title Text

For example, the color of the above "Title Text" was ruled "Blue" inside cascading style sheet, but then redefined as "Green" via a php variable, which was used inside a different kind of cascading style sheet (see below).

If your browser shows the above title text as green, then this technique works for your browser. As such, this technique allows you to use css variables just like other variables in many other languages.

While I thought of this technique independently, and for my own use, it has been addressed before in the Internet literature (i.e., Google search for "php css variables"). However, I did not find any reference that presented the technique with such simplicity.

The technique simply requires two things:

   1. Use a php suffix stylesheet as show below;

<link rel="stylesheet" href="style.php" media="screen">				

   2. Use a PHP Heredoc to encapsulate CSS as show below.

header("Content-type: text/css");
$color = "green";        // <--- define the variable 
echo <<<CSS   
/* --- start of css --- */
	color: $color;  /* <--- use the variable */
	font-weight: bold;
	font-size: 1.2em;
	text-align: left;
/* --- end of css --- */

Between the open and close php CSS statement, you can add as much css as you want, or not. You can have your "standard" css in one file and your "variable" css in another or place all in the same file -- it doesn't make much difference.

One of the things that has always bothered me in css has been defining colors. Sure, you can use the word-colors like red, blue, green, and such. But, these are producing error warnings in W3C validation. The W3C wants everyone to use numbers for color.

Normally, that's OK if you have just a couple of colors, but on some of the sites I've worked on I may have a dozen or more colors. As such, they become difficult to keep track of and who can look at a six character sequence and know what color it is, not me. So, I prefer using the above technique to define colors, like this:

  • $brown = "#442E18";
  • $green = "#42B988";
  • $blue = "#4FC4D7";
  • $menuUp = "#42B988"; // lite green
  • $menuDown = "#BDE7D5"; // dark green

Then in my CSS, it's a simple matter to know, find, and change what color I'm using for a menu item "at rest" (i.e. $menuUp) or "clicked" (i.e. $menuDown).

Also, if at some later date, you need to change a color of something, you don't need to wade through all your css to change a color -- you just do it in the heading one time and it's done. Now, that's simple!

Please note that the php suffixed file is loaded each time the page is called whereas the css file is loaded only once. As such, it may make sense to break your stylesheets into "standard" and "variable" css files. However, IMO, that's not a problem.

Please donate $5 below for my development effort -- thank you.

This technique W3C validates under both HTML 4.01 Strict and CSS guidlines.



quagga   Thursday, February 26, 2009 08:34
That´s a great idea. I`ll try it inside my next project because this could be the workaround I`ve been searching for a long time.
Thanx a lot ..
Luca   Thursday, March 12, 2009 03:22
Good idea, but I think this is a cleaner way:
h2 {

color: #
font-weight: bold;
font-size: 1.2em;
text-align: left;

Heredoc may be faster to write, but in a 3-400 (or more) lines css, in case of changes or debugging, it's easy to get confused when you need to search your variables. With the "classic" method you get them with a glance
Luca   Thursday, March 12, 2009 06:08
Sorry, I didn't read the "Please No HTML or other code" above.
I simply meant to completely separate php code from css using "echo" to retrieve the variable instead of embedding the variable in Heredoc
tedd   Thursday, March 12, 2009 08:12

Mine is an example of how you can use a PHP variable inside css -- it works.

As for getting confused, I think searching through 400 lines of code changing every occurrence of #442E18 to #42B988 is much harder than changing a single line.

As for the "classic" method, I don't know what that is. But I do know that when my css gets to the 400 line level, it's time to re-evaluate the css.
Cakes   Tuesday, April 7, 2009 23:04
This might be a little off topic, however, currently I am trying to use an echo statement to output a php variable. That's the simple part, but what I wanted to do was encapsulate that variable with a div to style it.

I won't post the code here, but basic premise is echo string of text: div : php variable : end div : string of text; I can get everything to print but it seems the div is completely ignored.

Any thoughts?
tedd   Wednesday, April 8, 2009 09:57

Without seeing the code, I really can't tell you exactly what is going wrong, but using an echo in php is very simple AND most importantly php does it's thing before the browser even see's it.

For example, if I had html statement of <div class="red"> This is text </div> that's absolutely no different than using <?php echo ('<div class="red"> This is text '); ?>

Both will produce the same result.

Show me your code. (Use the html less-than character for the right angle bracket).


Cakes   Wednesday, April 8, 2009 10:14
Thank you for your response, turns out I actually had the code correct but as I was very tired yesterday working on it, I was coding the wrong section of my website which is why what I was seeing on the screen and what I was thinking I was typing weren't lining up.

So frustrating when that happens isn't it? Well thank you for the help anyway!! You have a great website here.


Arthur   Wednesday, July 22, 2009 06:31
I love the idea of a php stylesheet but why is it I can't find anyone who's been able to successfully cache the file? Isn't the whole Idea of a stylesheet to save users from downloading uneeded styles?? I see on this page you have gzipped your styles but they don't cache? How can this be achieved, it sure is nice to cut 70% off the file size of a style sheet but when you have to download it on every page you visit what's the point?
tedd   Wednesday, July 22, 2009 11:16

The whole idea of style sheets is NOT that they are only downloaded once, but rather style sheets are a better way to handle styling than to embed it in html.

PHP is loaded every time the web page is called, so it should not come as any surprise that it's not cashed. Besides, what if your style sheet changes depending upon the user, or time of day/month/year, or any number of other factors. Style sheets need not be static to work.

As for downloading, are you kidding me? It is certain that both computers and access to the Internet are becoming faster. While download time was a thing to consider in the old slow dial-up days, download times now for simple things like stylesheets are not even noticeable.

If you want to speed things up, there are many other things to consider before a simple stylesheet.


Sage   Friday, October 16, 2009 00:44
Cool article.

Though it really isn't that hard to look at hex and have an idea of what color it will be.

The first two are Red, Second two are Green and the final two are Blue.

Red + Green = Yellow, 2-1 ratio for orange, 1-2 ratio for lime green
Red + Blue = Magenta, 2-1 ratio for red violet, 1-2 ratio for violet
Blue + Green = Cyan, 2-1 ratio for aqua, 1-2 ratio for teal.

All colors equal is a shade of gray.

Each digit can have 15 values and the numbering system is based on 15 instead of 10. FF=256, 00=0, 0A=10, 10=16.

Most people just use pairs (Web Safe):

00, 11, 22, 33, 44, 55, 66, 77, 88, 99, AA, BB, CC, DD, EE, FF

It seems complicated but it's not a lot to remember. You can look at 33FF00 and say "Well there's a TON of green, a little red and no blue. That's going to be green with a hint of yellow. Since at least one value is 00 it will be a fully saturated color."

Some colors ARE hard to figure out. Brown is actually orange but you have to add some blue and use low numbers (brown is darker than orange. So 663311 should be brown-I'm not testing this as I write so feel free to try my numbers and see if I know what I'm doing)

Pink can be simply red with equal green/blue values or magenta with a high green value. (I. E. FFAAAA = light pink; FFAAFF = a different type of light pink.)

After you experiment you figure it out. It's kind of fun.
Cem Kalyoncu   Friday, October 16, 2009 01:09
I dont get the idea of using all in PHP CSS. Its basically uneditable by any CSS aware editors. You can easily embed PHP into CSS not the otherway around. Observe

.body {
font-size: 14px;
tedd   Tuesday, October 20, 2009 12:17

If you don't get it, that's fine. This is simply one way to do what I said it would do.


Hussain   Tuesday, December 14, 2010 09:52
I have to admit that your method is just genius. So clean and so simple... In the beginning I thought this will never work, and didn't do indeed for me but later I found out that I had some comments in the beginning of my style.php file, I removed them and huuuuuuurrrrrrrrrraay every thing worked perfectly.

Thank you so much Sir :)
Hussain   Tuesday, December 14, 2010 10:18
Please Ted, I have another problem regarding this issue... I have a PHP variable $params which is a list of values that I will use as values of my css properties... The question is how to make $params visible inside style.php?

I will be appreciative for your advice...
Thank you
Ferge Billett   Tuesday, February 8, 2011 14:06
That was brilliant :-) I´ve been looking for a solution like this. Thanks, you made my day :-)
Nathan   Thursday, March 31, 2011 20:07
Just stopping by to show an easier way to enable PHP variables in CSS and you can even keep the .css extension.

Step 1: Create an .htaccess file
Step 2: Insert this code into your .htaccess file
AddHandler application/x-httpd-php .css
Step 3: Insert this code at the top of your .css file

Stwp 4: Enjoy! You can use CSS below the Step 3 code as you normally
would, but you can also use PHP above yoru CSS, and plug the
variables into the CSS.
Nathan   Thursday, March 31, 2011 20:11
Step 3: Sorry, it was cut out due to being in enclosing tags. Here is the code for Step 3

?php header("Content-type: text/css; charset=UTF-8"); ?

(Make sure to use the PHP enclosing characters (eg. > and

"Post a Comment" has been deactivated.

I'm sorry, but there is just too much spam to review to provide answers. For example, for every honest question, there are over 1000 spams. I am leaving the comments here so that they may help others.

I find my time better spent providing more examples and attending to clients.