Thursday, November 18, 2010

CSS Sprites

In the field of Web performance, CSS Sprites is one useful skill to merge small images into a bigger one (also called master image) to save number of HTTP requests and to reduce download size. There are a lot of discussions and explanations about CSS Sprites, but the root is simple - rely on CSS background-position property to display partial of bigger image. I don't want to explain the ins and outs of this skill, but want to put some excerpts here for quick reference.

One typical case is building a grid of images and devising a way to get each individual cell out of the grid, we can store all buttons/navigation items/whatever we wish in a single master image file, along with the associated “before” and “after” link states.

CSS sprites are a way to reduce the number of HTTP requests made for image resources referenced by your site. Images are combined into one larger image at defined X and Y coorindates. Having assigned this generated image to relevant page elements the background-position CSS property can then be used to shift the visible area to the required component image.

In this case, multiple images used throughout a website would be combined into the so-called “master image.” To display a single image from the master image, one would use the background-position property in CSS, defining the exact position of the image to be displayed. Any hover, active or focus effects would be implemented using the simple definition of the background-position property for the displayed element. CSS sprites are commonly used, particularly for navigation (such as for hover effects), icons and buttons.

CSS sprites group multiple images into one composite image and display them using CSS background positioning. You can save a significant amount of HTTP requests by consolidating your images into one or more composite sprites and using CSS to selectively display parts of the sprite within your web page.

Yahoo! uses a number of CSS hacks to allow for different browsers in their code.They also create different style sheets optimized for different user agents, a non-trivial amount of work. They include the backslash hack, underscore hack, voice family hack, and property:value; hack which is part of another CSS hack.

The smaller size of sprites is due to the reduced overhead of multiple color tables and formatting information required by separate images. To maximize accessibility and usability, CSS sprites are best used for icons or decorative effects.

There are a bunch of tools for CSS Sprites and image optimization.
CSS Sprites Generator

The background-position property sets the starting position of a background image. It is supported in all major browsers. For this to work in Firefox and Opera, the background-attachment property must be set to "fixed". For more information, check out CSS background-position Property

No comments:

Post a Comment