Dynamic CSS stylesheets with PHP.

In this tutorial, I will show you the basics of how to create a dynamic CSS stylesheet using PHP. In certain cases, you may want to dynamically display a color or style that is based on a value in your database or a configuration file. Example: The users of your website can select a background colour for their profile.

Let’s take a look at a simple example of a PHP file that outputs CSS:

<?php

//Set the content-type header and charset.
header("Content-Type: text/css; charset=utf-8");

//Setup our colour variables.
$backgroundColor = '#000000';
$textColor = '#FFFFFF';

?>

/** CSS begins **/
body{
    background-color: <?= $backgroundColor; ?>;
    color: <?= $textColor; ?>;
}

Explanation:

  1. We set the content type to text/css. This tells the browser that the output should be interpreted as CSS. We also set the charset to UTF-8.
  2. We created two PHP variables: $backgroundColor, which contains the hex value for the color of our background, and $textColor, which contains the hex value of our text. For this example, I’ve used “#000000” (black) for the background and “#FFFFFF” (white) for the text color.
  3. We then output some CSS as normal, filling in the blanks with our PHP variables.

Here’s an example of a HTML page including a PHP stylesheet:

<html>
    <head>
        <meta charset="UTF-8">
        <link rel='stylesheet' type='text/css' href='style.php' />
        <title>Example</title>
    </head>
    <body>
        Hello world!
    </body>
</html>

As you can see, we simply include the style.php file as if it was a CSS file. Note that you will have to change the extension of the file with mod_rewrite if you want the filename to contain a .css extension instead of a .php extension (if you are serious about implementing a dynamic stylesheet that is outputted by PHP, then this is probably the best course of action to take, as older browsers may not accept the .php extension).

If you run the example above, you will see that the webpage has a black background color and white text that reads “Hello world!”