Like any programming language, CSS can be used in many ways while still achieving the same result. And although sometimes there isn't necessarily just a single 'correct' way to achieve a certain goal, one thing we can all agree on is that clean optimal code is always better than bloated code.
With this in mind I thought I'd share some of the techniques that if you aren't already practising them, maybe this article will inspire you to start.
Use CSS Shorthand
This is the art of combining all the properties of an element into a single line. Some examples:
h1 {
font-weight: bold;
font-size: 3em;
line-height: 3.2em;
font-family: Arial;
}
...can be shortened to:
h1 { font: bold 3em/3.2em Arial }
Likewise,
body {
background-image:url(myimage.png);
background-position:top;
background-repeat:no-repeat;
background-color:#ffffff;
}
...can be shortened to:
body { background:#fff url(myimage.png) no-repeat top; }
Tip: Hex colours can be shortened by dividing them in 'half'. Examples:
#cccccc can be #ccc
#ff0000 can be #f00
Padding and margins can also be shortened:
#header {
padding-top:10px;
padding-right:20px;
padding-bottom:30px;
padding-left:40px;
margin-top:10px;
margin:right:10px;
margin-bottom:10px;
margin-left:10px;
}
...in this manner:
#header {
padding: 10px 20px 30px 40px; /* Just remember the order is clockwise - top right bottom left */
margin:10px;
}
Grouping
When repeating the same CSS for multiple classes you can combine them into a single group using comma separated declarations. Example:
.div01 {
background:#fff url(myimage.png) no-repeat top;
}
.div02 {
background:#fff url(myimage.png) no-repeat top;
}
.div03 {
background:#fff url(myimage.png) no-repeat top;
}
...can be shortened to:
.div01, .div02, .div03 {
background:#fff url(myimage.png) no-repeat top;
}
Serve up an optimised version of your style sheet
There are a stack of good CSS compressors online and they are very good at doing the same thing - changing your style sheet to be as optimal as possible. In some cases I've seen style sheets reduced by nearly 50% of the original size.
The only problem is that optimised style sheets can be insanely difficult to read, especially once the white space is removed. But if you want your server side site to be as slick as possible it's OK to serve up an optimised style sheet and keep your hand coded version local for easier editing.
When you're ready to upload your modified CSS, just remember to run it through a CSS compressor again first. Here's a few:
If anyone has any other tips for optimising CSS, feel free to share them below.


Jasmine
What a cool way to do font styles.
Another thing I do is padding: 20px 10px instead of padding: 20px 10px 20px 10px;
Monday 28th December 2009 | 10:06 AM Reply Comment URL Profile Back to top