CSS with PHP using PHP variables

Filed Under (CSS, PHP) by khawaib on 07-12-2009

Tagged Under : , , , , , , , , , , , ,

Recently one of my client asked me to add the functionality for users of their custom Content Management System(CMS) to give them more control over layouts etc. Using CSS in PHP makes it really easy to have styling flexibility.

Following steps are involved to write CSS via PHP.
Create CSS file as a PHP file

Set its content type using the following code

header("Content-type: text/css; charset: UTF-8");

Create PHP variables as you would normally in other PHP code. You can also bring variable data from database etc.

<?php
$myVariable = '#000000';
$myLeftColHeight = '500px';
?>

Outside your PHP tags you can write all of normal CSS code. Where ever you need to write the variable value just echo that variable not PHP way.

#myLeftCol {height:; color:;}

Final Code for stylesheet.php:

header("Content-type: text/css; charset: UTF-8");
$myVariable = '#000000';
$myLeftColHeight = '500px';
?>
#myLeftCol {height:; color:;}

Leave a Reply