How do CSS sprites work?

瘦欲@ 提交于 2019-11-27 15:22:29

The example you need to study is the following:

#nav li a {background-image:url('sprite.gif')} #nav li a.item1 {background-position:0px 0px} #nav li a:hover.item1 {background-position:0px -72px} #nav li a.item2 {background-position:0px -143px;} #nav li a:hover.item2 {background-position:0px -215px;} 

Sprite.gif is a big image containing all the smaller images in a grid (doesn't have to be). You then use positioning to display just that part of the sprite that contains your image.

There are online tools that given a set of images returns a big sprite image with the coordinates of where to find the smaller images.

A List Apart has a good article on them: CSS Sprites: Image Slicing’s Kiss of Death

All it means when you do spriting is that your small images are tiled on a single image file. You can create this single image file yourself if you have a decent image editing program. Then you can use the css background-position property to specify the piece of the image to use for that sprite.

Look here at Google's sprite that they use for iGoogle. You are just combining the images into one large image. That way you make one request. You then use background positioning and height and width to select which part of the image you want.

This also works really well for images that change on hover, as the hover state is already downloaded and does not have any delay.

Let's say you have button which changes its background image when it's moused-over. Mouseovers need to happen instantly to give good feedback to the user. If you just simply switched the image on the button, a browser might have to go to the server to fetch the image, which would spoil the effect. By using a CSS sprite, you have each image loaded and ready to go on the button instantly.

Also, some browsers "flicker" when you switch images. CSS sprites avoid this flicker issue which can sometimes happen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!