An important part of a user’s experience on your website is the time it takes for pages to load. Web pages with more pictures can take longer to load and require several server requests. Instead of using many pictures on your site, you can compress all of your images into an image sprite and use CSS to display different parts of that same picture at different locations on the page. This reduces the time it takes to load your pages, and only takes a bit more work.
To make an image sprite, you will need an image editor such as Adobe Photoshop or GIMP. Simply make a new project, import the photos you need for your page, align them, flatten the image, and save. You will probably want the images to be arranged in a grid-like fashion as this will make it easier to display them with CSS later. However if the sizes are not uniform, you do not really need to worry about this. You will eventually need to find the exact location of each image from the top left corner, its width, and height. Keep in mind that you will likely want to create your sprite after you finish collecting all your pictures; otherwise, you will have to create your flattened image more than once. An example of a sprite is given below.
To display the different parts of the image on different places in your page, follow the example below to make your CSS.
As you will notice, CSS properties are defined for each image in the sprite. The “left,” “width,” and “height” indicate the position in pixels from the left edge of the browser to the picture, the height of the picture, and the width of the picture respectively. The property “background:url(‘/path/image.png’) 100px 50px;” sets the position relative to the left and top where the image should be taken from the sprite, and the sprite’s file path. For example, if you wanted part of the sprite that was 20px by 30px, 15px from the left in the image, and 100px from the top, you would specify, “height:20px;width:30px;background:url(‘/path/image.png’) 15px 100px;”. You will also notice that the style for “a:hover” has been defined for each image class. This sets the picture that is displayed when the mouse is hovering over that specific HTML element. In this particular example, when the mouse hovers over the “home,” “contact,” or “about” links, they appear blue as on the left half of the sprite. Other CSS selectors such as “visited,” “focus,” and “active” can produce useful effects upon other circumstances.
Image sprites can help to lower the load time of pages on your websites, keeping users happy with the site’s speed. You should use them whenever you have many pictures to display because they can give a significant boost to your site.