Dynamic CSS

October 15, 2012Category: Tutorial, WebTags: ,

So for a long while I’ve wanted to be able to dynamically update CSS. This is especially useful in creating a dynamic WordPress theme framework. I’ve finally figured out a way to do so, and it’s really simple. There are three steps.

Step 1:

Rename your CSS file from .css to .css.php.

style.css
style.css.php

Step 2

Update the link in your HTML file from …

<link rel="stylesheet" type="text/css" media="screen" href="style.css">

… to …

<link rel="stylesheet" type="text/css" media="screen" href="style.css.php">

Step 3

At the top of your CSS document, insert this:

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

That’s it! Now you can put in whatever CSS you want statically, plus insert PHP variables the same as you’d do with HTML.

Static:

body {
    background-color:rgb(200,230,255);
    margin:0;
    padding:0;
}

Dynamic

body {
    background-color:<?php echo bg_color_light; ?>;
    margin:0;
    padding:0;
}