Home Account

simple css compiler written in php

2012-07-28 20:56 dennis iversen

Tags: php css

This must be the most simple CSS compiler I can think of. It does not have the powers of less and other CSS compillers, but it is much more simple, so that you will be able to use it within a minute - and maybe it is sufficient for your project. The following 3 files should just be placed in the same directory in order to make this work.

Here we go:

We have a file called constants.php where we put our 'rules':

<?php

// constants.php
$search = $replace = $vars = array ();

$vars = array (
    '{color_error}' =>      '#f60051',
    '{color_1}' =>     '#000', 
    '{font_header}' =>          'bold 175% Georgia, serif',
    '{color_2}' =>          '#777',
    '{color_a_1}' => '#0066CC',
    '{box_border_1}' => 

        // box border
    '    padding: 10px 20px 20px 20px;
    border: 2px solid #CCCCCC;
    box-shadow: 2px 4px 4px 1px grey;
    -moz-box-shadow: 2px 4px 4px 1px grey;
    -webkit-box-shadow: 2px 4px 4px 1px grey;',

    // box border 2
        '{box_border_2}' => 

        // box border
    '    padding: 1px 2px 2px 2px;
    border: 1px solid #CCCCCC;
    box-shadow: 2px 4px 4px 1px grey;
    -moz-box-shadow: 2px 4px 4px 1px grey;
    -webkit-box-shadow: 2px 4px 4px 1px grey;',

    '{color_3}' => '#eff',
    '{color_4}' => '#070',
    '{color_bg_1}' => '#fff',
    '{color_bg_2}' => '#eee'

);

$search = array_keys($vars);
$replace = array_values($vars);

Now we have some variables that can be searched for in a template and substituted. We take a base template which could look like this. In this short example it is only a couple of rules being used, but it shows the idea:

#form_error li {
    color:{color_error};
    text-decoration: underline;
}

.headline a {
    color: {color_1};
    text-decoration: none;
}

.headline {
    font: {font_header};
    color: {color_2};
    text-decoration: none;
    text-transform: uppercase;
}

.block {   
    width: 150px;
    font-size: 1.1em;
    {box_border_1}
    background-color: {color_bg_1};
}

Then we have out compiller which looks like this

<?php

// compile.php

$str = file_get_contents('css_template.css');
include_once "constants.php";
echo $str = str_replace($search, $replace, $str);

In order to create a css style from our template and our constants we now just runs the following command:

php compile.php > compiled.css

This page has been requested 5041 times