Related Tags

html
css
web development

# How to use CSS Sprites

## Sprites and why they’re used.

A Sprite is several images merged into a single image. The reason for its usage lies in how the Hypertext Transfer Protocol (aka HTTP) works. Whenever a webpage is fetched by HTTP, all of the images on the webpage are fetched in separate requests to the server. This uses a fair amount of bandwidth that could ​be saved by using sprites. Despite being a collection of images, a sprite only requires one request to the server to get the required images since those images are all stored in one file.

## How to use Sprites in CSS.

The example above shows how sprites are used in CSS. In the CSS tab, two ID selectors have been defined. The first one is for Educative’s graphical logo and the second one is for the text logo. The background attribute is used to identify the locations of both images within the original image. The format to do so is, background: url(image location), distance from left distance from top.

The Original Image

In the example above, the distance for the graphical logo was $120$ pixels from the left and $90$ pixels from the top. Similarly, the distance for the text logo was $17$ pixels from the left and $165$ pixels from the top.

The minus signs in the code are there because the more right something is, the more negative it is on the horizontal axis and the lower something is, the more negative it is on the vertical axis. The top left of the image is the origin, where the coordinates are (0, 0).

RELATED TAGS

html
css
web development