December 22nd, 2007 at 3:32 pm

Optimize your CSS

CSS files are the most downloaded parts of a website, as they are usually loaded with every webpage. Also, CSS files usually contain a lot of, from a technical point of view, unnesseccery characters. Therefore it is a good idea to optimize your CSS file(s) for faster loading. A good tool to remove pretty much all spare characters is the CSS compressor, which can reduce the file size of your CSS up to 25%. Of course, you should always keep a “source” version for modifications.

That tool of course is not able to optimize your CSS semantically, this must be done by you. Semantic optimization means that you should scrutinize your CSS file for redundancy. Do you possibly define background-image, background-position and background-repeat separately? Merge them into a single statement like background: #fff url(image.png) top left; — you need the first ones only for overwriting a single other property. (That’s why they are called Cascading Style Sheets.) Same goes for margin, border and padding with their -top, -right, -bottom, -left: Use them only for overwriting. In all other cases, merge them into one statement: For example, margin: 5px 2px; will assign a margin of 5px to the top and bottom, and 2px to the left and right. margin: 5px 2px 3px; will assign a margin of 5px to the top, 2px to the left and right, and 3px to the bottom. And margin: 5px 2px 3px 4px; will assign a margin of 5px to the top, 2px to the right, 3px to the bottom, and 4px to the left.

Other possibilities: Consider using relative paths to images instead of absolute ones. Remove unneeded definitions (or comment them out before sending them through the compressor). Combine multiple selectors in a single one (e.g. if you have #content_left a, #content_right a it could be possible to use #content a instead).

Optimizing your CSS by compression and good semantical style will shrink your CSS by 30-60%. This will make the loading of a webpage from your website noticeably faster, even with a fast connection.

Leave a Comment