Currently Browsing: Home » Stunningly Simple CSS Minifier

Stunningly Simple CSS Minifier

Creating a beautiful and eye-catching website can often require you to have a hefty CSS file. Unfortunately, this side-effect takes away from your visitors experience; they spend more of their time downloading rather than viewing. In essence, a balance needs to be reached in order for full optimization.

CSS

Solving the problem

One simple way to achieve this balance is by using a minifier. By taking a CSS file in as input, a minifier removes white space and other unnecessary elements to significantly reduce file size.

Oops, did you forget about something?

At first glance, this seems to be a zero-drawback system. Upon closer inspection, it becomes apparent that removing white space creates poor formatting, a leading cause of what we call read-once write-once code. You might be able to edit the styles directly after creation, but in a few days or weeks, this task becomes tedious.

This is mainly why using online minifiers aren’t 100% supported. In fact, by creating your own minifer, there is a way to both keep formatting and produce minified code. You might think these are mutually exclusive. This post, which demonstrates how to create a stunningly simple CSS minifier, aims to prove you wrong.

Meet our dear friend: PHP

In our previous post, we showed you how to generate CSS using PHP. In this article, we will utilize a similar concept.

Before you can actually solve the minifier’s main problem, it is imperative to first write a minifier. Luckily, we have created an extremely simple PHP function to do so. In approximately 10 lines, the following code will finish over 90% of all possible minifications:

function minify( $css ) {
	$css = preg_replace( '#\s+#', ' ', $css );
	$css = preg_replace( '#/\*.*?\*/#s', '', $css );
	$css = str_replace( '; ', ';', $css );
	$css = str_replace( ': ', ':', $css );
	$css = str_replace( ' {', '{', $css );
	$css = str_replace( '{ ', '{', $css );
	$css = str_replace( ', ', ',', $css );
	$css = str_replace( '} ', '}', $css );
	$css = str_replace( ';}', '}', $css );

	return trim( $css );
}

Who knew simplifying CSS could be that easy? Using preg_match, the above code is able to replace extraneous white space with just a single character. It then proceeds to minfy even more elements using str_replace.

Huh? How am I supposed to use the above code?

Well, now that we have created our PHP function, you might wonder how to use it. The answer to this question stems, once again, from the previous article. Instead of linking to a css file from our HTML, we will actually refer to a php one:

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

Notice how we call our minify.php file with the parameter css. The value of css actually refers to the file we want to minify. With this in place, create the minify.php file and add in the function we previously created. In addition, place the following code at the beginning of the file:

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

$file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
if( !file || array_pop( split( '\.', $file ) ) != 'css' || strpos( $file, '/' ) !== false )
	die( 'Invalid Parameters' );

$content = @file_get_contents( $file );

The above snippet obtains the contents of the specified css file. To add security, it first verifies that the file name is not blank, ends in .css, and that it is located in the current directory. Feel free to edit the last setting as necessary by removing:

strpos( $file, '/' ) !== false

To complete our CSS minifier, all we have to do is call minify on the obtained content and then print it:

echo minify( $content );

Voila! You now have a fully functioning CSS minifier in minimal code. In addition, the formatting of your code stays 100% in-tact. All you need to do is edit the CSS file that you pass to minify.php in order to make changes.

Here is a simple copy-paste version of our code:

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

$file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
if( !file || array_pop( split( '\.', $file ) ) != 'css' || strpos( $file, '/' ) !== false )
	die( 'Invalid Parameters' );

$content = @file_get_contents( $file );
echo minify( $content );

function minify( $css ) {
	$css = preg_replace( '#\s+#', ' ', $css );
	$css = preg_replace( '#/\*.*?\*/#s', '', $css );
	$css = str_replace( '; ', ';', $css );
	$css = str_replace( ': ', ':', $css );
	$css = str_replace( ' {', '{', $css );
	$css = str_replace( '{ ', '{', $css );
	$css = str_replace( ', ', ',', $css );
	$css = str_replace( '} ', '}', $css );
	$css = str_replace( ';}', '}', $css );

	return trim( $css );
}
?>

Thanks for stopping by!

Tags:

This entry was posted on Sunday, September 13th, 2009 at 02:28:56. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.