Article

CSS Optimization Tips

Appnovation Blog Default Header

Do you want to reduce your css files to help page load times, well here are a few helpful tips that will become second nature to you after repetitive usage.

1) Shorten Hex Colors. If you need to have a color that uses the same character such as #FFFFFF. You can simply write #FFF. This works anytime you need to specify color.

/* Original*/ .header { background: #FFFFF; background: white; } /* Optimize */ .header { background: #FFF; }

2) Combining margin-top, margin-bottom, margin-left, and margin-right. Instead of having 4 lines for each margin or padding you can combine them into one. I always remember the order by thinking it goes clockwise, starting at the top followed by right then bottom and finally left.

/* Original */ .classname { margin-top: 10px; margin-right: 3px; margin-bottom: 4px; margin-left: 8px; } /* Optimize */ .classname { margin: 10px 3px 4px 8px; }

3) Combine top and bottom or left and right margins. In the situation where you want to have both left and right be the same pixels you can combine it.

/* Original */ .classname { margin: 7px 10px 6px 10px; padding: 4px 5px 4px 5px; } /* Optimize */ .classname { margin: 7px 10px 6px; padding: 4px 5px; }

4) 0 pixels actually equals 0. You can actually remove the "px" if the padding is actually 0.

/* Original */ .classname { margin: 0px; } /* Optimize */ .classname { margin: 0; }

5) Combine the styles for background and font You can combine background-position, background-repeat, and background-color into the background attribute. This can be used with "font" attribute also. In the following example "700" also is equivalent to bold.

/* Original */ .bg_wrapper { background: url('image.png'); background-repeat: no-repeat; background-color: #000; background-position: 0 10px; font-weight: bold; font-size: 1.3em; font-style: italic; font-family: "FB Armada", sans-serif; } /* Optimize */ .bg_wrapper { background: #000 url('image.png') no-repeat 0 10px; font: 700 italic 1.3em "FB Armada", sans-serif }

6) Reducing whitespace This maybe harder to read as a user and harder to manage but this is what most CSS compressers end up doing.

/* Original */ .classname { margin: 10px 3px 4px 8px; } /* Optimize */ .classname { margin: 10px 3px 4px 8px; }

7) Finally you can pass your css to online optimizers The best one out there is probably Icey's CSS Compressor (opens in new window)

Get the thinking,
before everyone else.

One considered email a month. New essays, field notes from live engagements, and the occasional strong opinion. No noise.