Implement CSS Sprites


Part One Chapter 14

CSS

When your mobile web pages are using large number of images (e.g. more than 20), the web browser must request and download each of them. Requesting and downloading each image files can take up considerable time and slow down your mobile web page's loading.

However, the images can be combined into a single image. This will reduce the number of http requests and enable your mobile pages to load significantly faster. The combining of images is possible with CSS sprites. The steps for CSS sprites are:

  • Create the image.
  • Position the image.
  • Use the images.

Combine and Create the Image

For example, we have two small images each is of size 50 pixels by 50 pixels.

  • We will create a single image by combining the 2 images. The combined image will become a large image of size 100 pixels by 50 pixels (i.e. width is 100 pixels, length is 50 pixels).
  • We will name the combined image “combined.png”.

CSS Sprites

Position the Image

The one combined image is actually made up of 2 images where the first image is right above the second image.

Go to your page's CSS file and add this line below.

  • “firstimg” is the class name that we have defined.
  • The size of the first image (within the single larger combined image – “combined.png”) is specified by width and height.
  • “background:url(images/combined.png)” – We will later use the image as a background image in the “div” tags.
  • “0 0px” specifies the image's coordinates which means the image starts off from the top left corner of “combined.png”.
.firstimg {width:50px; height:50px; background:url(images/combined.png) 0 0px;}

We will also add the following line to the same CSS file. This line is for defining the second image (within the single larger combined image – “combined.png”). Note the image starts off from “0 -50px”.

.secondimg {width:50px; height:50px; background:url(images/combined.png) 0 -50px;}

Use the Images

To use the first image in your mobile web page’s HTML code, specify the class “firstimg” in an empty “div” tag.

<body>
<div class="firstimg"></div>
</body>

To use the second image in your mobile web page’s HTML code, specify the class “secondimg” in an empty “div” tag.

<body>
<div class="secondimg"></div>
</body>


Gordon Choi's Mobile Website Book has been available since November 2016.







Content on Gordon Choi's Mobile Website Book is licensed under the CC Attribution-Noncommercial 4.0 International license.

Gordon Choi's Mobile Website Book

Gordon Choi’s Other Websites:
SEO Expert in Hong Kong (Gordon Choi’s Blog)
Analytics Book