To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Server-side generated CSS

Server-side generated CSS is one of many techniques that can be used to generate CSS on-the-fly. This gives the developer the option to include different features of server-side languages, such as PHP, including variables, functions and more. As a matter of fact, this website uses some server-side generated CSS which is shared with others.

Server-side vs. client-side

There are two sides to web development in general - client-side (front-end) and server-side (back-end). Server-side always comes first in the generation of pages, with client-side running when the browser receives the page and it's associated files.

CSS is a client-side language as it is interpreted by the user's browser. PHP is a server-side language as it is interpreted by the server's PHP interpreter.

This particular article talks about using PHP to generate a CSS file.

Getting started

In a new file, style.php, the following PHP code is required:

PHP
<?php
	header("Content-Type: text/css");
	$contents = "html{background:green}";
	echo $contents;
?>
		

Templating the CSS

To make it easier to generate the variables and so on in the PHP, it is a good idea to create a text file with placeholders for variables:

Text
#main {
	background: /MAIN_BACKGROUND/;
}
div.el {
	color: /MAIN_COLOUR/;
	font-weight: /FONT_WEIGHT/;
}
		

Now using some PHP tricks, the placeholders are replaced:

PHP
<?php
	header("Content-Type: text/css");
	$contents = file_get_contents("placeholders.txt");
	$contents = str_replace("/MAIN_BACKGROUND/", "#f00");
	$contents = str_replace("/MAIN_COLOUR/", "#000");
	$contents = str_replace("/FONT_WEIGHT/", "500");
	echo $contents;
?>
		

On the basis that this PHP file is called style.php and is located in the root directory of the website, the following is all that is needed in order to use this file as CSS:

HTML
<link rel="stylesheet" type="text/css" href="style.php">
		
Provide feedback on this page
Comments are sent via email to me.