Pages

Sunday, September 27, 2009

CSS sprites

CSS sprites are a great way to SPEED UP your application, and simplify the design changes. You save in two ways:

1) amount of HTTP calls, each call has a relatively large overhead compared to small icon file it fetches

2) putting many small files into single saves a lot of "weight" as well

Take example of these icons, each about 37 kb...

When combined into a single file they weight ONLY 49 kb, that is from about total of 250 kb, including all other icons I have put into it.

You want to put your files into a narrow image to make it convenient for yourself, you will use your favorite graphic tool (Pixelmator, Photoshop) to measure where the icon starts. I made all my icons 30 pixel tall.

Here I am interested in Facebook (heart icon) and I see that it starts at about 1264 pixels (X coordinate), since Y is ALWAYS at 0 pixels, and width and height are 30 pixel, that is all I need...

Finally, I write a simple to understand CSS style:

.icon_favorite {

background: url("images/icons001.png")no-repeat;

background-position: -928px0px;

width: 30px;

height: 30px;

cursor: pointer;

}

.icon_facebook {

background: url("images/icons001.png")no-repeat;

background-position: -1264px0px;

width: 30px;

height: 30px;

cursor: pointer;

}

.icon_edit {

background: url("images/icons001.png")no-repeat;

background-position: -1299px0px;

width: 30px;

height: 30px;

cursor: pointer;

}

Then GWT code to use that style, notice I use HTML, not Image for that icon.

HTML submitToFacebook = new HTML("");

submitToFacebook.setStyleName("icon_facebook");

submitToFacebook.setTitle("Click to post this recipe on Facebook");

...

HTML edit = new HTML("");

edit.setStyleName("edit_facebook");

edit.setTitle("Click to edit this recipe");

...

And that is it...

Updated (after receiving some feedback):

I still like the CSS sprites solution because it gives a full control to the graphic (HTML/CSS) designer, but GWT developers should definitely take a look at ImageBundle.