How to Write More Efficient CSS to Speed up Your Site


By

As part of my new position as CTO of Speckyboy, I’ve decided to write a series of articles that will help you understand what it takes to make a truly fast site. As you may have noticed Speckyboy just got a shot in the arm recently and is running a heck of a lot faster.

This is because of all of the tips that I will be listing in the “Website Speed” series, where the focus is 100% on load times.

Why should you care about your CSS? Why when products from Adobe and others output entire websites with HTML and CSS, all pre-made and ready to deliver to the customer?

The reasons are simple, all of those ‘pop-out’ builder apps will add lots of unnecessary CSS and HTML in lazy ways. Slow websites suffer from high bounce rates and lower search engine rankings.

In surfing terms, ‘pop-outs’ are created on a production line and used by beginners that surf for a day, while a custom board is handcrafted and used by a pro. People use pop-outs as they are heavier, go slower and offer the beginner a more stable platform to work on. Whereas a custom board is lighter and tailored exactly for the rider so that they can perform to the top of their ability. The same it true when you develop web pages.

You can, of course, use pop-out website creators to make your websites, but you will be showing the rest of the web producing world how much of a novice you really are, as your website will be slow to load and heavy on kb and have lots of extra HTML and CSS to make it work.

#1: Write your own Custom CSS and HTML

Custom CSS and HTML will always make your site fast. Always try to reduce the amount of DOM elements you use, or in other words if you don’t need to have a HTML tag there get rid of it.

Here is a good example of where a List is used where it does not need to be, in the footer of a website

<div class="example-footer-1">
<ul>
 <li>&copy; <a href="#"> my website 2011</a></li>
 <li><a href="#">privacy statment</a></li>
 <li><a href="#">sitemap</a></li>
 <li>site created by <a href="#">my amazing company</a></li>
</ul>
</div>

235 characters of HTML

.example-footer-1 {
  padding:20px;
  border-top:solid 1px #cccccc;
  border-bottom:solid 1px #cccccc
}
.example-footer-1 ul {
  list-style-type:none;
  padding:0;
  margin:0}
.example-footer-1 ul li {margin-right:3px; display:inline}

215 characters of CSS

where as

<div class="example-footer-2">
<p>
 &copy; <a href="#"> my website 2011</a>
<a href="#">privacy statment</a>
<a href="#">sitemap</a>
site created by <a href="#">my amazing company</a>
</p>
</div>

197 characters of HTML

.example-footer-2 {
  padding:20px;
  border:solid 1px #ccc;
  border-width:1px 0
}
.example-footer-2 p {padding:0;margin:0}
.example-footer-2 a {margin:0 3px 0 0}

153 characters of CSS

Click here to see the two different examples in a single demo file.

The things that were different in example 2 were

1) set the border width for all borders then unset the border width for the sides rather than exclusively setting the border for both top and bottom.

2) reduced the border width color by 3 characters using the shorter form of #ccc rather than #cccccc.

3) did not use a list as this really is not a list of things. Just used A tag only in the HTML. It is common practice for many designers and pop-out makers to use a list here.

4) changed the list for a paragraph tag to keep HTML validation correct, which reduced the links by 9 characters per list element. ‘<li>’ and ‘</li>’ are not needed any more, and changing ‘<ul>’ and ‘<p>’ saved a character top and bottom.

5) changed the margin statement from margin-right:3px to margin:0 3px 0 0, although it does not save any space on this statement if your using more than one margin statement at once it will.

#2: Get rid of un-needed spaces, tabs and carriage returns

If you check with the W3C, WordPress or others they recommend that you write your CSS in a top to bottom style, for example, the official way to write CSS needs carriage returns, tabs, and spaces to aid reliability.

.example  {
	padding : 20px;
	border : 1px solid #ccc;
	border-width : 1px 0px;
}

Character count 90, 4 carriage returns and 3 tabs
If you want a faster site you should minify that as much as possible when you code it:

.example{padding:20px;border:solid 1px #ccc;border-width:1px 0;}

Character count 64, no carriage returns, no extra spaces, no extra characters and no tabs.

What happened here was simple, the extra fluff was removed. It will still validate quite happily but will not take up as much space.

To save yourself a bunch of time doing this by hand you could use a text editor or IDE to do most of it for you. Here are a hand full of find and replace statements you can run.

  • replace ” {” with “{“
  • replace ” }” with “}” [1]
  • replace “: ” with “:” [1]
  • replace ” :” with “:”
  • replace “; ” with “;” [1]
  • replace ” ;” with “;” [1]
  • replace “, ” with “,”
  • replace ” 0px” with ” 0″
  • replace ” 0em” with ” 0″

[1] it is worth running these commands 2 or 3 times in a row to get rid of all those un-needed spaces.

Remember : CSS minification tools will never be as efficient as you can get by hand. Take W3 Total Cache’s minification, for example, it does not remove the spaces before/after a colon, before the opening curly brackets, or after a comma. What W3 total cache does well is remove carriage returns that help to make your file readable at all.

#3: Get rid of un-needed semi-colons at the end of each CSS statement

Taking our efficient no spaces, tabs or carriage returns CSS statement we can make it 1 character shorter by removing the last semi-colon from the end of the statement

.example{padding:20px;border:solid 1px #ccc;border-width:1px 0;}

… becomes …

.example{padding:20px;border:solid 1px #ccc;border-width:1px 0}

So our 64 characters long statement becomes 63 characters long.

If you consider that there are often upwards of 200 CSS statements in a CSS file, this saves 1 character per statement, so for example with a 200 statement file 200bytes are removed. Easily removed if you look for “;}” and replace with “}”

#4: Learn CSS Properly

You might think I am teaching you to suck eggs with this statement, but please stay with me on this one. I often see from other people’s designs and code that they do not understand how CSS works properly. They have most likely worked things out by reading websites here and there, and not necessarily knowing the truth of a situation. After all there is a lot of the blind leading the blind out there on the Internet. So cut out the bullshit and get yourself some proper understanding of CSS. For example on nearly every website I have re-coded for a corporate I have seen:

li {list-style-type:none}

where it should not be applied to the List Element but the list as a whole, like this

ul {list-style-type:none}

Or take these examples of either wasted space or silly code

#header {width:auto; margin: 0 auto;}
#footer {margin: 0 0px 0 0px; padding:0 0 0px 0}
#sidebar {
background-image: url(images/image.png);
background-position: center top;
background-color:transparent;
background-repeat: no-repeat
 }

Where #header must have a specific width applied for the auto margin to center it, so 2 bits of wasted code only leaving the margin-bottom and top of 0 to be active.

The #footer could have just been margin:0;padding:0;

#sidebar could have just had background:transparent url(images/image.png) no-repeat center top;

There are usually many more on every site that I have made quick, be that for a major corporate or for a small design company. This usually stems from two places, a designer who does not really code, or a back-end coder who does not really know CSS.

Do yourself a favour and get some books on the subject, don’t rely on websites to give you the answers here. Personally, I find the Sitepoint books the most readable. Oh, and do try very hard to understand the difference between browsers and their CSS level so that you can gracefully degrade your code when still having to support IE6 for corporates.

#5: Watch out for Wasteful CSS Resets

Many people use a CSS reset at the start of their CSS code to try to get a level playing field across all browsers. While I find this a good idea, the execution is often misguided.

Take this CSS reset as used by mashable.com defined by Richard Clarke

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent; }

This could not be more wasteful in many places. Lets take it apart for a second.

footer, nav, section, label, dfn, cite, kbrd, code, samp, b, i, strong, em, canvas, tr, thead, tfoot, tbody, span, var & div do not need to be in this list at all as they are already pre-defined by all browsers as no padding, no margin, no background, no borders, no outline, don’t have an applied font size. Wasted space.

sup, small & sub should not have font-size of 100% applied to them as they should be a different size than the rest of the text fo making it 100% kills the point of it. Again wasted space.

sup and sub are not supposed to have a vertical align of baseline, sup makes it small and above the line, sub makes it small and below the line.

I’ll argue that th and td should have vertical-align:top as that is almost always the way that they are used and that they actually need to text-align:left to make them consistent as on some browsers th is in the middle and some it is on the left.

So lots of wasted space and also lots of extra applied items that the browser has to think about before processing the entire page. Because these rules come first in the page they will be applied to all items on the page and then later CSS will overwrite it. Basically this slows down everything and makes your CSS file bigger than it needs to be. A waste of time all round, don’t be fooled into thinking that the ‘cream of the web’ know what they are doing, they just cut and paste also.

#6: gzip your CSS

Gzip is much like normal zip that you use almost everyday. It is a tool used to compress files down to their smallest size so that when they are sent to the browser they use less network bandwidth.

If your server allows it, be that apache, tomcat, lighttp or IIS, always gzip your CSS. Be aware that many hosting companies will turn off gzip for their servers as it takes additional processing power to make it that way and they do not want their servers to have any lag. Also be aware that if you are an exceptionally popular site the extra processing to gzip your content can be detrimental to your server performance, you may have to invest in extra processing power.

There are different levels of gzip’ing, on the whole most people use ‘-9’ or ‘level 9’ gzip’ing as it is the one that makes the files the smallest, but also takes the most processing power.

Greater details and full instructions for this will be coming soon in the “Configuring Servers for Speed” part of this series.

Remember : Not all browsers can handle gzip’ing and some browser security tools stop it’s usage, so focus on having a small CSS file in the first place.

#7: Put Stylesheets at the Top of the Head

Always, always, always put the stylesheet at the top of the HEAD section of your HTML, just below the title. This is because it wants to be downloaded as quickly as possible so that it can be applied to the page. Do not for any reason put a STYLE tag inside the body of your html unless it is 100% necessary for that specific task, add it to your external style sheet.

#8: Always use an External Stylesheet

External style sheets are good as they can be gziped and cached on the browser, if you put the style inline in the head it will be loaded freshly each time the page is loaded, making the response time slower.

#9: Don’t use CSS expressions

CSS expressions are poorly supported, and take additional processing power. If you want to, for example, have a different background color based on the time of day, do it at the server end by generating your CSS dynamically, or write some funky Javascript that does the same task after all of the files have loaded for the page.

#10: Don’t use @import use link

Some people use @import to include CSS into their HTML, this is a very bad idea as it slows things down, use the standard link syntax and do remember to setup the right media type in it:
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" >

#11: Setup browser caching on your CSS files

Caching on the browser is where you tell the browser that the CSS file is not going to change for a period of time. This could be 1 hour, 1 day, 1 month, 1 year, 100 years or whatever you choose. As long as the browser has not had it’s cache emptied it will re-load your CSS file from it’s local storage and will not ask your server for it. This has 2 distinct benefits, firstly that it loads less files from the server meaning that the server can have more connections at once, and secondly that the CSS file is loaded in miliseconds from the local memory and not 100’s of miliseconds from the server.

Greater details and full instructions for this will come in the “Configuring Servers for Speed” part of this series.

Remember : The browser can only make so many connections at once to the server, it has to wait for each connection to become available before it can be used, going elsewhere than the server allows for the browser to be doing other tasks such as downloading images or HTML.

#12: Use a Content Delivery Network (CDN)

A content delivery network is a global infrastructure of servers that only serve content. The idea being that if your server is located in California and you have a vistor from Germany, then without the CDN they will have to get all of the files from California making lots of extra network time on the trip there and back. However with a CDN the user would not have to go all the way back to California for that information, they would go to the local server in Germany. In fact depending on your CDN hosting company it might be better than just Germany that they go to, if they were for example from Munich then they might go to a Bavarian server.

A content delivery network is really only a viable option to those that have very busy sites, and that is all down to cost. For example the S3 CDN from Amazon web services, the last time I checked, would need a monthly investment cost of $150 minimum and quickly ramping up to very large figures depending on the options chosen. This does place the CDN outside the realm of most websites. However, as a web designer/creator you could invest in a CDN and re-sell that to all of your clients within your hosting package.

Here is a list of top CDN hosting companies…

Akami – The big daddy (or should I say big wave) of all content delivery companies, the first and still the best, but mega bucks to use. Definite corporate choice, very good people to work with, very helpful.

Max-CDN – As used by SpeckyBoy and supported out of the box by the W3 Total cache plugin for WordPress, good pricing.

Highwinds – As used by myself for the Share and Follow plugin for WordPress as it offers security unlike many of the others and great pricing.

Amazon S3 – From Amazon Web Services. Expensive but very good, however, the pricing options do add to the confusion and much time invested to get the right deal.

Limelight – No personal experience with using this CDN, but I have not heard of any bad reports.

Remember : Use a different DNS name than your servers DNS name as the name for your CDN network or it will send pointless cookie info. Don’t use a sub-domain either, it will still send that cookie info.

#13: Try to reduce the usage of Decedent Selectors

Decedent selctors are often used by designers to explicitly define how an element of the page should look. Going back to the example at the top of the page:

.example-footer-1 {
padding:20px;
border-top:solid 1px #cccccc;
border-bottom:solid 1px #cccccc
}
.example-footer-1 ul {list-style-type:none;padding:0;margin:0}
.example-footer-1 ul li {margin-right:3px; display:inline}

(Carriage returns added for readability)
it would infact be much faster to process if setup as:

ul {list-style-type:none;padding:0;margin:0}
li {margin-right:3px; display:inline}
.example-footer-1 {
padding:20px;
border-top:solid 1px #cccccc;
border-bottom:solid 1px #cccccc
}

(carriage returns added for readability)

This is quicker because the browser does not have to keep on looking for .example-footer-1 and it’s decendents when it knows that ul and li have been setup. It’s a ‘set and forget’ method that you have to try to use.

This can be applied to all of your sites design to try to get the most out of the speed of a site, but of course this is a ballancing act between speed and beauty.

#14: Add Things Together to Save Space

Very often in the creation of a website most of the CSS code is duplicated many times throughout the page. So for example there might be a case where the same margins, border and padding is used but a slighlty different tweak made for each one.

.list1 {margin:0; padding:0; border:solid 1px red}
.list2 {margin:0; padding:0; border:solid 1px green}
.list3 {margin:0 5px; padding:0; border:solid 1px black}

where this could be much more efficently written as

.list1, .list2, .list3 {margin:0; padding:0; border:solid 1px red}
.list2 {border-color: green}
.list3 {border-color: black;margin:0 5px}

On a personal level the ones that I tend to do a little different are the rounded corners. Rather than applying them to each CSS element in turn I tend to create 1 or 2 classes that have the rounded corners setup already and apply them to the HTML. For example

.rounded
{-moz-border-radius:3px; border-radius:3px; -webkit-border-radius:3px}

.rounded-big
{-moz-border-radius:15px; border-radius:15px; -webkit-border-radius:15px}

.rounded-top {
-moz-border-radius-topleft:3px; border-top-left-radius:3px;
-webkit-border-top-left-radius:3px; -moz-border-radius-topright:3px;
border-top-right-radius:3px;  -webkit-border-top-right-radius:3px;
}

#15: Combine all of your CSS into 1 file

All web servers and pages work faster when they have a reduced number of connections for each page. So with that in mind it’s much quicker to have only 1 CSS file that is called (gzip’ed, cached and on your CDN) rather than having many. Each request for a new file will take additional time, often will need a DNS lookup, exchange cookie information and have to wait for it’s connection with the server. Cut out all that crap by just adding all your CSS into one file.

#16: Try your hardest to get your CSS file under 25k

If you can get your files to under 25k then iPhone and other mobile devices will cache it. Very important if they are your target audience. If the file is cached it will not be downloaded again.

#17: if you don’t use it don’t send it

Lets imagine that you are creating a site for a Florist and are adapting the Twenty Ten theme for WordPress for it. Can you think of any occasion where the CODE tag is used at all? Nope either can I. So don’t send that CSS to the client. This methodology should also be applied to the CSS reset you might use also, if they don’t use abbr, sub, sub blockquote etc, remove it from your CSS coding. Likewise if the site you are making does not have comments, don’t include all that CSS that deals with comments.

It’s a simple rule but often forgotten, especially when adapting another persons work as your starting point.

#18: Minify your CSS

After you’ve taken the time to do all of the space saving you can, the final thing you would want to do is minify your CSS to make it as small as possible. This is what you should do before officially having production worthy CSS.

There are a few different ways of doing the minification, you can do it before you upload your CSS with tools like this online CSS compressor, a local application on your PC such as YUI Compressor or on the server as a server task which is called each time the CSS file is loaded for a browser. As ever, it’s best to minify first and then upload as there is then less server resources needed to provide the minified file.

Do remember that if you minify it before putting it on your server, it will be impossible more or less to read the file any more.

Roundup

Well, that is the end of this first part of the “Website Speed” series. I will be covering many more items in future editions to give you a well-rounded set of tools to help make things as quick as they can be.

Do remember that every one of these items comes from many years of experience of doing just this, so there is no wasted effort in any of these 18 items. Each one is going to help to make your site faster.

Of course if you can’t wait that long and need someone to a magic speed wand waved over your site, drop me a mail and myself and my team will gladly sort you out on all speed fronts.


Top
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.