{"id":4906,"date":"2009-12-03T07:21:57","date_gmt":"2009-12-03T14:21:57","guid":{"rendered":"http:\/\/css-tricks.com\/?p=4906"},"modified":"2013-06-27T14:04:39","modified_gmt":"2013-06-27T21:04:39","slug":"css-variables-with-php","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/css-variables-with-php\/","title":{"rendered":"CSS Variables with PHP"},"content":{"rendered":"

When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.<\/p>\n

<\/p>\n

Style.php<\/h3>\n

Instead of using the .css file extension, use .php<\/p>\n

<link rel='stylesheet' type='text\/css' href='css\/style.php' \/><\/code><\/pre>\n

Content-type<\/h3>\n

At the top of your new style.php file set the Content-type back to CSS:<\/p>\n

<?php\r\n    header(\"Content-type: text\/css; charset: UTF-8\");\r\n?><\/code><\/pre>\n

Set up variables<\/h3>\n

Now you can set up variables for whatever you like:<\/p>\n

<?php\r\n    header(\"Content-type: text\/css; charset: UTF-8\");\r\n\r\n   $brandColor = \"#990000\";\r\n   $linkColor = \"#555555\";\r\n   $CDNURL = \"http:\/\/cdn.blahblah.net\";\r\n?><\/code><\/pre>\n

Use variables<\/h3>\n

Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.<\/p>\n

#header {\r\n   background: url(\"<?php echo $CDNURL; ?>\/images\/header-bg.png\") no-repeat;\r\n}\r\na {\r\n  color: <?php echo $linkColor; ?>;\r\n}\r\n\r\n...\r\n\r\nul#main-nav li a {\r\n  color: <?php echo $linkColor; ?>;\r\n}<\/code><\/pre>\n

Extend the power \/ Other ideas<\/h3>\n