开发者

How do CSS sprites work?

开发者 https://www.devze.com 2023-01-01 16:25 出处:网络
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.

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 cl开发者_运维百科ear 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.]


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.


CSS Sprites: What They Are, Why They’re Cool, and How To Use Them

How do CSS sprites work?


(source: css-tricks.com)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消