Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS Image Sprites Technique

CSS Image Sprites Technique


Image sprites

Image sprites are a collection of individual images.

A webpage with many images may take a long time to load and generate multiple server requests.

Using image sprites reduces the number of server requests and saves bandwidth.


Image sprites - a simple example

Instead of using three separate images, we use this single image ("img_navsprites.gif"):

navigation images

With CSS, we can display only the part of the image we need.

In the example below, CSS specifies which part of the "img_navsprites.gif" image to display:

Example

img.home

{

width:46px;

height:44px;

background:url(img_navsprites.gif) 0 0;

}

Try it »

Example analysis:

This is the simplest way to use image sprites; now we add links and hover effects.


Image sprites - creating a navigation list

We want to use a sprite image ("img_navsprites.gif") to create a navigation list.

We will use an HTML list because it can contain links and also supports background images:

Example

#navlist{position:relative;}

#navlist li{margin:0;padding:0;list-style:none;position:absolute;top:0;}

#navlist li, #navlist a{height:44px;display:block;}

#home{left:0px;width:46px;}

#home{background:url('img_navsprites.gif') 0 0;}

#prev{left:63px;width:43px;}

#prev{background:url('img_navsprites.gif') -47px 0;}

#next{left:129px;width:43px;}

#next{background:url('img_navsprites.gif') -91px 0;}

Try it »

Example analysis:

Now let's start the positioning and styling of each specific part:


Image sprites - hover effects

Now we want to add a hover effect to our navigation list.

| lamp | The :hover selector is used to display an effect when the mouse hovers over an element**

 ****提示:** :hover 选择器可以运用于所有元素。 |

| --- | --- |

Our new image ("img_navsprites_hover.gif") contains three navigation images and three more images:

navigation images

Because this is a single image rather than 6 separate image files, there is no loading delay when the user hovers over an image.

We add the hover effect with just three lines of code:

Example

#home a:hover{background: url('img_navsprites_hover.gif') 0 -45px;}

#prev a:hover{background: url('img_navsprites_hover.gif') -47px -45px;}

#next a:hover{background: url('img_navsprites_hover.gif') -91px -45px;}

Try it »

Example analysis: