5 Tips for optimizing and cleaning up CSS
Here are some easy but often overlooked tips to write clutter-free, efficient CSS and save file size at the same time:
1. Use shorthand
CSS properties like padding, margin, background, font and border allow usage of shorthand. Combining values using shorthand help in cutting down code and coding time.
For example:
padding-top:4px;
padding-bottom: 3px;
padding-right:0px;
can be written as:
*hint : top – right – bottom – left*
2. Omit units like px / em / % when value is zero
As you may have noticed in the above example, I have eliminated px from the properties that are of value 0. Zero (0) doesn’t require units. 0px is the same as 0em or 0%.
3. Color Prefixes
Typically HEX codes used to define color values are 6 characters long. However, certain color combinations can be reduced and represented in 3 chars.
For example:
can be written as:
also
can be written as:
4. Group Elements
If there are multiple elements like h1, h2, h3 with common properties, instead of declaring them separately it helps optimize your CSS by combining them, like as follows:
padding:0 ;
margin:0;
color:#000;
}
5. Use a compressor
Once you are done with your CSS wizardry, it is a good idea to use a CSS compressor tool to shed the excess load off your CSS files. There is a bunch of such services available online, like: cleancss.com, codebeautifier.com, and cssoptimiser.com to name a few. Make sure you attempt optimizing your CSS this way at the end of your project, just before going live because it is likely that you will be served up with a human unreadable (but browser friendly) block of code.
Latest posts by Smarajit Dasgupta
- Playing with HTML5 - July 29th, 2011
- CSS Tutorial - June 7th, 2011
- Introduction to HTML5 input types - April 1st, 2011
- Text level Semantics in HTML5 - March 17th, 2011
- Audio in HTML5 - March 4th, 2011
