Ask the CSS Guy

Keeping CSS file sizes lean for practicality and sport

One of the benefits touted by separating style from structure is smaller html file sizes. But with many sites, the accompanying CSS file(s) can offset the savings in size, with CSS declarations that can quickly add up. Doug Bowman's site, for example, has 50 KBs worth of CSS. Since CSS is cached, and therefore only downloaded once, and since a growing number of people are on broadband connections, some developers might not see this as a problem.

But there are still some dial-up users out there who still do value the time of initial page load. There are still server admins who care about bandwidth. And fortunately, there are still some web developers out there who not only still care about those dial-up users and server bandwidth, but also take great pride in keeping their CSS files as slim as possible. If you think that only comes by sacrificing readability and structure to the CSS, you may be surprised. Here are some tips in doing so.

1. Use shorthand properties

I thought I'd start by stating the obvious, and say that you should use CSS shorthand properties. (Is anyone learning CSS without learning these, too?) I won't go into all of the shorthand properties here (if you need to know all of them, use this handy page.

Basically, instead of declaring things this way:

#menu {
	margin-top:20px;
	margin-right:5px;
	margin-bottom:10px;
	margin-left:12px;

Do it like this instead:

#menu {margin:20px 5px 10px 12px;}

I'll get another obvious one out of the way with my next suggestion.

2. Cut Colors in Half

Hexidecimal color codes can be shortened in many cases. #ff6600 can just be #f60. This only works when the values are given in pairs, but it's still helpful. White and Black are both common declarations, so instead of #ffffff and #000000, use #fff and #000 respectively. This may not save much, but every little bit helps.

3. Plan ahead

Backpack enthusiasts care about every ounce they carry when hiking. The weights of the tent, flashlight, even silverware, was an important factor when purchasing and packing. Similarly, one can plan ahead when creating a site, and can shave off some bytes in the process.

When planning what CSS is used, make sure to research to find out how many different layouts your page can have. Are there some pages with three columns and some pages with only two, but the column with the main content will be the same in each? Then use classes and IDs wisely.

For example, take the following xhtml for a page with two columns:

<div class="layout2col">
	<p>Dogs smell.</p>
</div>

... and on another page with three columns:

<div class="layout3col">
	<p>More about smelly dogs.</p>
</div>

The CSS for that site might look like this:

.layout2col {width:400px;}
.layout2col p {
	font: normal 1em/1.2em Verdana;
	color:#333;
	}
.layout3col {width:250px;}
.layout3col p {
	font: normal 1em/1.2em Verdana;
	color:#333;
	}

It's ok, but a bit repetitive. If the xhtml could instead look something like this:

<div id="content" class="layout3col">
	<p>More about smelly dogs.</p>
</div>

The following, more concise, CSS could be used and achieve the same results as above:

#content p {
	font: normal 1em/1.2em Verdana;
	color:#333;
	}
.layout2col {width:400px;}
.layout3col {width:250px;}

4. Ids, Classes, and File names

If a naming convention is used for ids, classes, and images, it can mean a big difference in the CSS file size.

For instance, instead of have a ul with an id of #primarynavigation and another ul with an id of #secondarynavigation, use #nav1 and #nav2 instead. Instead of #header and #footer, maybe use #head and #foot. Instead of a class of .content, maybe use a class of .main.

Image names are another place you can apply this technique. Instead of naming the background image to an h1 "background_h1.gif", consider a name like "bg_h1.gif".

5. Change Directories

File names aren't the only place to trim some letters. Consider the directory where images are stored. The image directory has to be referenced with every mention of a background or list-style image. Many people call that directory "images", but what if it was named "img", or just "i"?

#logo {background: #fff url(../i/logo.gif)}

Not only would you save a few letters over the course of a CSS document, but it could be enough to keep many lines from wrapping, and therefore adding to the readability of a CSS file.

6. Consider ditching alternative fonts

I was always told to offer alternative fonts, such as the following:

p {font:normal 1em/1.2em Verdana,Arial,sans-serif;}

...which says that paragraphs should be of font-family Verdana, and if Verdana isn't available on the user's system, use Arial, and if Arial isn't available, use whatever the default sans-serif font would be.

But I think some fonts, such as Verdana and Georgia, are on everybody's system, so why bother offering a back-up? You could save a few bytes by ditching those alternatives:

p {font: normal 1em/1.2em Verdana;}

I usually only do this for Verdana, Arial, and Georgia. If a less boring font was to be used, it would still be good to list alternatives.

7. Work in one CSS file, but publish another

One easy way to trim file size is to take out comments and white space for the final version of the CSS file. Comments, white space, and putting one declariation per line are all great ways for developers to organize and write their CSS. But once you're ready to publish that file, make a copy of it and strip all the comments and white space from the copy. Upload that new slim file to your server. After all, browsers don't care about your CSS comments and white space. If you ever need to troubleshoot, rewrite, or add to your CSS, you can do so in your 'working copy'. Then make another slimmed down copy to republish. CSS Tweak is a great service for stripping white space and comments.

Knowing that one will later publish a slimmed down CSS file can be quite freeing to a developer, and may result in that developer using more thorough comments than one would otherwise. And comments help everyone, even the person who originally wrote them.

I'd love to hear of any other techniques people find helpful.

Comments (70)

glen wallis said:

Great article. Really good advice...particularly with regard to bandwidth. Re-naming "images" to "img" and "styles" to "css" may seem like a little thing, but it all adds up.

From little things big things grow.

Marty said:

Surley the best way to improve speed for dial up users is correct optimisation of images. If each letter of text is 1 byte and a 56k modem can transfer 56,000 bytes a second (theory) surly optimising text files is a waste of time. Slightly compressing a large image on the site will save more precious bytes than spending ages thinning out a style sheet.

Paul said:

Good article. Using shorthand properties in CSS can significantly reduce the size of a stylesheet. My personal favourite for this technique is explained in greater detail on 456 Berea Street. I also agree wholeheartedly with the previous comment on image optimisation.

CSS Guy said:

Marty - Good point about the images. That would probably warrant its own article or two, which I'm sure has been done by people of greater expertise than myself. I think if people were educated on when to use .gif vs .jpg, other facets of image optimization may fall into place. Thanks for offering to the discussion.

Bill Dashfield said:

Load time is important on our site; my approach is
* minimize image size
* keep CSS compact and optimised - easier to maintain.
* use Gzip (at server) to compress text (HTML, JS, CSS) files, reducing text file size by 66% or 75%, and reducing overall page load time by 20-40% with a single change. Uncompression has been long supported by browsers (HTTP 1.1 I think), is invisible, automatic and degrades gracefully. It is fast at the browser, though processor intensive at the server. Each page is cached once gzipped. (As my site is hosted externally, and has dynamic content, I'm still working on getting gzip enabled for HTML). With Gzip saving so much, I now leave comments in.

* Minimise numbers of files - some tools suggest each file increases loadtime by 0.2 secs in redtape.
Good design can greatly reduce the number of small image files. Currently, with variable layouts, IE specific and test files, I have up to 6 CSS files for a page - too many, even though they are all small and cached. I hope to optimise to 3 or 4.

PS 56Kb is 56 Kilobits per second = 1/8 of 56 KiloBytes per second. In practice it is much lower than that, even on a good line.

Chris Botman said:

All up, good intentions, but I disagree with points four and six.

Point four, using shorter, less descriptive names, will make the job harder for new or maintenance developers (or even for yourself after you haven't worked on the site for a year), and I would argue the performance gain would be unnoticeable for most sites--even on dial-up.

If it was really a big deal, I'm sure you could extend point seven further by finding an optimization program to strip both your HTML and CSS down to one character class names, etc. You would continue to work with fully descriptive names, while serving optimized files.

As it is, Gzip does something like that (and more), so unless you're serving pages to people who are on dial-up and can't use Gzip, any changes you make will have almost no effect at all.

Another option altogether, if you want a quicker upfront load, is to have a dedicated style sheet for the homepage. The larger style sheets for the rest of the site can be loaded (and cached) when the visitor decides to travel further into the site, and are, assumably, willing to wait that extra two seconds.

Point six is silly because you are removing functionality (the ability to substitute similar fonts) for the sake of a few bytes. You'd be better off pruning a few sentences of the site's copy.

That's what I think anyway. :)

Cheers.

Chris Botman said:

Ah, as this blog entry on site performance by Yahoo points out, the bottleneck in loading a page is caused by the number of components (images, scripts, style-sheets) a browser to has fetch, not the actual HTML (I'll make an assumption and say CSS too).

"Premature optimization is the root of all evil." :)

By the way, I found your site and the Yahoo link from the Max Design mailing list.

CSS Guy said:

@Bill and Chris-

I never thought of using Gzip. For true competitors :)

I like the idea mentioned of using fewer images. A very real and practical scenario for that would be for CSS image rollovers.

I can see your point about the naming conventions for filenames not being immediately understood by other developers. Short of that, though, I feel like someone would know that 'bg_h1.gif' stood for a background for an h1 element. And 'nav1' and 'nav2' vs 'primarynav' and 'secondarynav'. Makes sense to me. I can see taking that too far with single character class names, but I wouldn't promote that.

Quick poll: Who doesn't have Verdana?

Geoff said:

Changing 'images' to 'img' or 'i' - what a waste of time.

I put all images used in the css straight into a 'styles' folder with the css, so that I don't need any path info in the css file at all. I don't do it to save characters, but to keep all the style images separate from the content images, which go in an 'images' folder.

CSS Guy said:

@Geoff -
I like that idea.

Pepe said:

PLEASE I use to found open source css resources. I´m trying to make my oun web site but I don´t know where I can paste the css code ´cause I want it works.
Sorry about my bad english and thanks for your explanations.

Pepe.

CSS Guy said:

@Pepe

Place all your styles in a blank text file, and save that file as styles.css in the same directory as your html file.

Then, in the <head> tags of your html, paste the following line:

<link rel="stylesheet" type="text/css" media="screen" href="styles.css" />

Hope that helps.

hilary said:

I'd take issue with point 3. To make it work you've added "id="content" on every single html page which probably outweighs the css saving. (It might be a good thing to do for semantics, but not for load time.)

The way I'd shorten and simplify the css is like this:

.layout2col {width:400px;}
.layout3col {width:250px;}
.layout2col p, .layout3col p {
  font: normal 1em/1.2em Verdana;
  color:#333;
}

Note that I also think indenting slightly is well worth the whitespace cost.

Demian said:

Well, one good way to organize a CSS and make it smaller can be to give just stylefirst and then color (can be a separated stylesheet).
For example:

h1 { font: normal 1.8em/2em Verdana; }
p { font: normal 1em/1.2em Verdana; }

h1, p { color: #300; }

Regards.

Jermayn Parker said:

A agree that websites still need to be quick loading even though most have access to broadband. Some (including me) still have it. You raise some very valid points which I have not thought of before.

I personal disagree with getting rid of the index and comments in the style sheet. I myself hardly use them unless really needed but I think they are a vital element when used. I personally hate style sheets that have everything on the one line. To me it looks messy and cluttered.

I agree with the point about only having Verdana in the style sheet if thats the font your using. Makes sense.

However like some have mentioned I think the best way to get rid of the extra bytes is to slightly optimise the images. You can knock off quite a lot by a little optimising and you cannot even tell the difference.

Kyle Spaulding said:

Great topic, and well written While most people might find it easier to simply optimize images a bit more, rather than clean up a stylesheet, a larger website getting a lot of traffic can benefit greatly from these techniques.

For instance - for every byte that Google eliminates from it's main Google search page - it saves them ~$10,000 per year. Now that's an expensive byte.

R Walker said:

A good example of a site that optimises CSS while still allowing readability is http://1800reverse.com.au/css/classic.css

Once the CSS is finalised the "orig"inal CSS is run through http://www.cleancss.com/ to save almost a quater of the original file size.

Aukcje said:

Thanks for this very good article … Can i translate this and insert on my site in Poland? … Thanks

CSS Guy said:

@Aukcje:

Sure. A link back is all I ask.

Meble said:

CSS Guy: Can i too add this on mysite? Your side has very helpful articles.
Thanks and best regards

CSS Guy said:

@Meble:

Sure. I can't translate it on my own. :)

tanie linie lotnicze said:

Great blog CSS Guy.
Fantastic article covering some points I really needed some good usability info for.

Hotel w Lublinie said:

Thanks for this very good article … Can i translate this and insert on my site in Poland? … Thanks

CSS Guy said:

@Hotel:

Sure.

Prag Hotels - Unterkunft in Prag said:

Good tips. Thanks for taking the time to write it down.

strony internetowe said:

eee ... I couldn't spend so much money for that. After next, let me guess - 8 months, they'll realise something faster. Of course if you can swap CPU with new model but probably no.

Katalog said:

Great stuff, any information about new version of this?

skrypty CSS said:

The beginning of the year is a time for resolutions. Polls show that going on a diet is the number one resolution Americans make. After all that holiday eating we start eyeing our waistlines and promising ourselves to do something about it. It occurs to me that this same resolution should apply to webmasters this year.So raise your right hand and repeat after me: "I hereby resolve to slim down my CSS files for me, my readers and better search engine rankings.

Praca said:

Wow, it's really easy.

Biżuteria said:

The sites shown here are visually appealing. The use of css to handle the layout, graphics, backgrounds, links is very well handled. The only issue is the css over takes the message and clouds the content. Sometimes simplicity can speak volumes. Our initial designs for our firms site looked very similar to all the ones shown here. Is that a coincidence. I don’t think so. The web-designer was referencing these sites for layout ideas. I think that is common amongst many designers these days. There is so much out there that looks fantastic, that one feels the urge to do it themself. Most web 2.0 sites look the same. I think we can all agree on that.

Modeschmuck said:

thank you, this CSS file helped me very much.

Schliessershop Türschliesser said:

thanks alot, will use this now.......

Darmowa bramka sms said:

Thanks for this very good article

budowa domów said:

Great blog CSS Guy.
Congratulations

Dami said:

good article

linki sponsorowane said:

Nice site and good post

Uhren Onlineshop said:

This site is interesting and very informative, nicely interface. Enjoyed browsing through the site. Keep up the good work. Greetings

Uhren Onlineshop said:

This site is interesting and very informative, nicely interface. Enjoyed browsing through the site. Keep up the good work. Greetings

Robert said:

Helpful CSS-Codes and useful tips.
Thanks!

Książki said:

Yes, it's very intresting article.

upominki sklep said:

Very interesting article:) Good work:) Thank

duygu said:

thank you, this CSS file helped me very much. kisses:D

Unternehmensberatung Finanzberatung Mittelstand said:

Greatfull Information, congratulation

Tuning said:


Simple and beautiful, what can I say more. CSS is a very powerful tool that gives a web designer great power over their site if used properly

dental insurance said:

thank you, this CSS file helped me very much.

Hausschuhe said:

Hi, Thanks for very interesting article. I really enjoyed reading all of your articles. It’s interesting to read ideas, and observations from someone else’s point of view… makes you think more. Keep up the good work. Greetings,

Unternehmensberatung Mittelstand said:

Great Information, gratulation

Unternehmensberatung Mittelstand said:

There are goog and great Information, thank you

Tworzenie Stron said:

Hello
Very good article
I was sreaching this infomrations in Internet
almost all day
Thx for this helpull info.

Greetings, Tworzenie Stron

arkadas said:

Alright, this is it… for real. I’m sticking with this design. I took this blank template and made a new theme from scratch, for the first time actually. This isn’t based on any other structure or theme for a change. Over the next little while I think I’ll make the mods of Balance and Cutline available that I had been using recently.

rowery said:

Helpful CSS-Codes and useful tips.

James Podatki said:

thank you a lot for the great idea

kredi said:

I agree with you, i always tryed to structure my css codes, but i have to admit that when i have not so much time or when i'm modifying something wrong i forget to maintain order in code.

zutestrane said:

Works fine for me , thanks

sexli said:

thank you

sex said:

thank you

haber forum said:

thank you

Poker said:

thanks for info

Quick Fresh Info said:

Good website - thank you

Stroje kąpielowe said:

Good site. Happy new year

kral oyun said:

Very interesting article Good work:) Thank

Tanie www Rzeszow said:

You are absolutelly right but it is not good solution for me

Pozycjonowanie Katowice said:

Very nice idea, but I think it is not good solution for me. :)

Aktorzy said:

this is wery nice idea, thanks for this.

shops eintragen said:

Very nice idea, but I think it is not good solution for me. :)

przepisy kulinarne said:

Very interesing article. Thanks for the article! As a full time developer, this information is exceedingly useful to me.
As a full time developer, this information is exceedingly useful to me. Very interesing article. Thanks for the article!

przepisy kulinarne | papryka said:

This is interesting article, I did not it think that it yes. Interesting it knew persons about this how much. Sorry if I wrote bad there now my English is novice and I do not it write yet good.

online shopping said:

One thing's for sure – nomatter what you do with CSS, it's still going to work five hundred times better than a full flash-site. With regards to those poor souls that are still on dial-up, flash sites must be an absolute NIGHTMARE. I can't believe how many companies will opt for a flash site and not realise that it does nothing for them – it doesn't work well with SEO, is hard to load, and often hard to use. CSS is 99.9% the best way to go regardless of the industry.

online shopping said:

One thing's for sure – nomatter what you do with CSS, it's still going to work five hundred times better than a full flash-site. With regards to those poor souls that are still on dial-up, flash sites must be an absolute NIGHTMARE. I can't believe how many companies will opt for a flash site and not realise that it does nothing for them – it doesn't work well with SEO, is hard to load, and often hard to use. CSS is 99.9% the best way to go regardless of the industry.

Airline Bewerten said:

Is that a coincidence. I don’t think so. The web-designer was referencing these sites for layout ideas. I think that is common amongst many designers these days.

 

Post a comment