DISCOVER
X

Optimize Your CSS by Removing Redundant Rules

May 13, 2013 10:08 pm Leave your thoughts
FacebooktwitterredditpinterestlinkedinmailFacebooktwitterredditpinterestlinkedinmail

CSSCSSBuilding a new website is always exciting, especially if its your own. First you design in your favourite graphic design software such as Illustrator, Inkscape, Photoshop or GIMP. Then you start applying the design into your website. The problem is that sometimes we get carried away with our CSS. We tend to want to get that pixel perfect sizes and positioning; while doing so, we keep adding rules to our CSS to fine tune the looks. While this might be okay in short term, this is not a very good practice down the track.
Hard to maintainConvoluted CSS rules are:

  • Bandwidth waster, as we could have saved a few bytes shaving off those replicated rules
  • Prone to introducing design bugs. For example we can end up with different shades of grey for example.
  • Hard to maintain (yes I mentioned it twice!). Everyone in your development team will end up using !important to get the future style going if you don’t optimise the css.

So, in order to remove the duplicated rules and sub-optimal rules, we can use these two tools:

  • CSS Lint (http://csslint.net/).
    • This tool will help eliminate non-best-practice rules. Such as using 0px instead of 0 for things with no values or identifying empty rules. I like to think this tool as “recommendations” only, unless you got some real error. We can’t really follow all the rules but just keep the recommendations in mind.
  • CSSCSS (http://zmoazeni.github.io/csscss/)
    • This tool will search for the duplicated rules in our CSS file. Eliminating duplicated rules will save on the size and simplifies the css rules for human consumptions.
    • As this tool is written on ruby, you’ll have to use gem to install it. Just follow the instructions on the website to install it.

Like other articles in here of course, I try what I write. Just running CSSCSS and identifying duplicated rules I managed to bring down the css style of this website from 16K to 15K :). Yes not that much, but by removing duplicated rules, if I ever want to change the font family I can do change it in one places, previously the font-family rule was duplicated in 5-7 different areas. Of course we can’t always do these kind of optimisation from the very start of the development, but there’s nothing stopping us running CSSCSS in multiple phases of the development.

In short, applying CSS Lint and CSSCSS will make our css much more readable, maintainable and optimised in the long term. So give this a go on you projects when you can.

 

FacebooktwitterredditpinterestlinkedinmailFacebooktwitterredditpinterestlinkedinmail
Tags: ,

Categorised in: ,