1. Home

  2. /
  3. Blog
  4. /
  5. Web
  6. /
  7. Dynamic CSS

Dynamic CSS

Date:

Cat.:

Tags:

,

[repost-link]

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;
}

Leave a Reply

Your email address will not be published.