How do CSS sprites work?

2020-01-29 14:16发布

I have 3 different images and want to create a sprite using CSS. I understand that will reduce HTTP requests. However, I am totally new to this concept and have no idea as to how to approach this.

What would be best bet for me? Also I have seen there are some CSS sprite generators where you submit a .zip of images and it combines them.

I tried doing that, but did not understood what was happening. Any guidance regarding creating and using CSS sprites would be highly appreciated.

Update: I have gone through the A List Part article but it was not very clear to me. Can someone provide an example of using a CSS sprite? [A short, self-contained example in an answer is preferable for SO than just a link to an example elsewhere. –ed.]

6条回答
\"骚年 ilove
2楼-- · 2020-01-29 14:48

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.

查看更多
Viruses.
3楼-- · 2020-01-29 14:58

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.

查看更多
对你真心纯属浪费
4楼-- · 2020-01-29 15:00

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.

查看更多
一夜七次
6楼-- · 2020-01-29 15:07

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.

查看更多
该账号已被封号
7楼-- · 2020-01-29 15:13

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

查看更多
登录 后发表回答