开发者

CSS - Sprites as background images

I have a web application whose performance I am working to enhance. In an attempt to do this, I decided to use css sprites. I have placed all of my images in a .png file called images.png.

CSS sprites have worked well for all css classes that just display an image once. However, several of my images 开发者_Go百科need to be repeated. For instance, I have a banner.png image used for the banner background. Whenever I set the background-repeat property, it seems that the image does not repeat. To show my CSS definitions, here they are:

Before CSS Sprites
------------------
.ghwc {
  background-image: url(/images/layout/banner.png);
  background-repeat:repeat-x;
  color:White;
  width:300px;
}

After CSS Sprites
-----------------
.ghwc {
  background-image: url(/images/images.png);
  background-repeat:repeat-x;
  color:White; 
  background-position:60px 319px; 
  width:300px;
}

My question is, how do I use CSS sprites for repeated images like backgrounds?

Thank you,


My question is, how do I use CSS sprites for repeated images like backgrounds?

You don't. That is simply not possible using CSS sprites. To do that, you would have to be able to specify an area of the image that is to be repeated, and to my knowledge that is impossible in both CSS 2 and 3.


You can do this if you're only background-repeat:repeat-x; as in the example, you just need to make all backgrounds contained within the sprite image container the same width and lay the sprite image file out vertically. Then your background position property will always have the first x position be 0 and the sprite is located with the second y position (e.g. background-position:0 0; background-position:0 -100px; background-position:0 -200px; etc) . This might not work across all browsers if you can't specify the exact height and set overflow:hidden.


Assuming your background image (images.png) shows at all, your code should work. If you want this to render correctly on Opera and Firefox, you'll need to add

background-attachment:fixed;

Edit: I just realized you're probably talking about a specific coordinate set in a "sprite" image comprised of several 'images'. You're not going to get any one particular area of an image to repeat like that. Crop the image to the size you're concerned about, then use the code you have.


If you want to use repeat-x, you must not put several images next to each other in your sprite as the whole sprite is duplicated in x-direction (as you already noticed). But you can put them in one vertical line. (The other way around if you want to use repeat-y. There is nothing like "background-crop" up to now (maybe in CSS4? ;) )

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜