WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

CSS Image Sprites



Image Sprites

Image Sprites is a collection of individual images.

Web pages with many images can take a long time to load and generate multiple server requests.

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



Image Sprites-simple example

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

navigation pictures

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

In the following example, the CSS specifies a portion of the image that displays "img_navsprites.gif":

Example

img.home
{
width:46px;
height:44px;
background:url(img_navsprites.gif) 0 0;
}
Try it yourself »

Instance analysis:

  • <img class="home" src="img_trans.gif" /> -Because it cannot be empty, the src attribute defines only a small transparent image. The image displayed will be the background image we specified in CSS
  • Width: 46px; Height: 44px;-define the part of the image we use
  • background: url (img_navsprites.gif) 0 0;-define the background image and its position (0px left, 0px top)

This is the easiest way to use image Sprites, now we use link and hover effects.



Image Sprites-create a navigation list

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

We will use an HTML list because it can be linked 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 yourself »
Instance analysis:
  • #navlist {position: relative;}-set the relative positioning of the position, let the absolute positioning inside
  • #navlist li {margin: 0; padding: 0; list-style: none; position: absolute; top: 0;}-margin and padding are set to 0, the list style is removed, and all list items are absolutely positioned
  • #navlist li, #navlist a {height: 44px; display: block;}-the height of all images is 44px

Now the positioning and style of each specific section: