Write CSS Dynamically For Php Application

Sometime in our application we need to manage the css dynamically with some condition. For example if I have 5/6 themes for an application and let user give the option to change the theme we have to change the theme dynamically again if we need to generate some conditional styles for different condition we need to generate dynamic styles. If we generate CSS with PHP it helps to keep various styles for different browser or different condition, no need to make different styles. Here with an example we can see…Save the styles with “.php” extension instead of “.css”.

The first line should be follows to set the output.

header("Content-Type: text/css");

That’s all now you can add any conditions php logic at the CSS. Such as:

<? if (stristr($browser, "MSIE") || stristr($browser, "Internet Explorer")) {
/* browser is Internet Explorer */
body {background-color: white; }
p {font-family: arial, sans, sans-serif;
font-size: 10pt;
font-color: blue; }
} else
if (stristr($browser, "Opera")) {
/* browser is Opera */
body {background-color: lightyellow; }
p {font-family: courier, monospaced;
font-size: 10pt;
font-color: darkgreen; }
<?php } ?>

The dynamic style sheet can then be called by an HTML document as usual.
<link rel="stylesheet" href="styles.css.php" type="text/css" />

If you use any php framework like codeigniter and you want to use any variable from to the CSS then simply pass the value of the variable at the time of call.

<link rel="stylesheet" href="styles.css.php?theme=black" type="text/css" />

header("Content-Type: text/css");
$theme = $_GET['theme'];
if($theme == 'black'){
// Write styles for black theme
<?php } else{ ?>
//Write styles for other theme
<?php } ?>

Is not very easy? I like the method of writing css with php very much. I think you also will enjoy using it. There are lots of benefits using it and you can understand when you use it.

Happy Coding…….


, , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: