A+ A-

Combine & Minify CSS with PHP

A fast website equals a good user experience. It also pleases search engine spiders.

Using a little PHP you can combine & minify all of your CSS files on-the-fly.

This not only reduces the overall filesize, but also minimises HTTP requests.


The PHP code.

<?php
header('Content-type: text/css');
ob_start("compress");

    function compress( $minify )
    {
	/* remove comments */
    	$minify = preg_replace( '!/*[^*]**+([^/][^*]**+)*/!', '', $minify );

        /* remove tabs, spaces, newlines, etc. */
    	$minify = str_replace( array("rn", "r", "n", "t", '  ', '    ', '    '), '', $minify );

        return $minify;
    }

    /* css files for combining */
    include('reset.css');
    include('application.css');
    include('responsive.css');

ob_end_flush();

Usage.

Create a file with the code above and save it as minified.css.php, then simply link to that file as you would normally for your CSS file:
<link href="assets/css/minified.css.php" rel="stylesheet">

All the CSS files you reference inside the script will be combined & minified at run time.


Conclusion.

This not only makes your web site faster, it also allows you to work with multiple files in development without having to manually compress each before pushing to production.

If you’re already using our CSS framework Workless, then you’re probably already using this method as it is built-in.

About Scott

Freelance Web Designer. Developer. SEO Consultant. WordPress Evangelist. Theme Creator. Reviewer @Envato. Founder iKreativ, LoveThemes, NakedApes & Creator of Workless

Join the Discussion.

Outdoor Apparel