Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize CSS file for speed

Tags:

css

I wonder how it's possible to optimize CSS file for faster loading, at the moment my CSS file is arround 2400 lines and it size is 54kb. None of the graphic elements is bigger then 4kb, so I believe CSS is reasson my website is rendering/loading slow.

That's just main CSS, on some pages, I'm loading additional CSS files.

like image 557
ProDraz Avatar asked Mar 12 '12 14:03

ProDraz


4 Answers

That's a lot of CSS. While a CSS "minify" tool is a good idea, you may want to take a manual pass over the file and look for rules that can be combined. For instance:

margin-top: 10px;
margin-right: 5px;
margin-bottom: 0px;
margin-left: 5px;

can be reduced to:

margin: 10px 5px 0 5px;

And even further to:

margin: 10px 5px 0;

Similarly, borders can be reduced:

border-width: 2px;
border-color: #123456;
border-style: solid;

This can be expressed as:

border: 2px solid #123456;

background, padding, and fonts are some of the other rules that can be written such that they are much shorter and more efficient. Here's a good article on CSS Shortcuts.

The CSS minifiers are useful tools, but I'm not sure they are able to rearrange your code into the shortcut format.

like image 181
Surreal Dreams Avatar answered Nov 17 '22 21:11

Surreal Dreams


You can minify CSS code using the following tools:

CSSMin http://code.google.com/p/cssmin

Minify http://code.google.com/p/minify

YUI http://developer.yahoo.com/yui/compressor

CSS Minifier http://www.artofscaling.com/css-minifier

CSS Tidy http://csstidy.sourceforge.net

like image 26
Andriy Budzinskyy Avatar answered Nov 17 '22 21:11

Andriy Budzinskyy


Have you minified the file? http://www.minifycss.com/css-compressor/

I wouldn't say 2400 lines of css is excessive. So maybe the speed issue is something else? Check out a web developer plug-in for your browser and see how many resources are being loaded.

Try combining images into sprites, using SmushIt to compress images and minifying your css/js.

like image 25
Stanley Avatar answered Nov 17 '22 19:11

Stanley


On top of compressing, you should consider splitting your CSS file down into multiple files. If you have specific classes that are only ever used in a specific page you should have a CSS file for THAT specific page that isn't loaded anywhere else.

You should also make sure that you are correctly inheriting style items so that you are not re-writing the same elements over and over again.

like image 36
Patrick Avatar answered Nov 17 '22 19:11

Patrick