css sprite with negative background positions not clear

放肆的年华 提交于 2019-11-28 09:15:21

问题


I am working on some existing code where they are using css sprites. There is big image and its been used for to display all the images.

Its basically a Ul and li elements. The each li element uses this image and uses a background position.

I understood the css sprites completly ,its for better performance. But only thing which is not clear is why the x and y positions start with negative margins. Most of the images in the sprites are getting retrived by using something like

-540px -30px like this

I was watching that image on the browser and it shows up correcetly and they should with 0,0 right.

am i missing something here


回答1:


Just think about the element as a peep-hole, with the sprite image being moved behind it.

0,0 is the top left corner of the peep-hole.

Depending on which part of the huge sprite image you want to see, you need to give it a negative offset.

-50, -20
|-----------------------------------------------|
|                                               |
|       0,0                                     |
|       |-----|                                 |
|       |     |  <--- Peep-hole                 |
|       |-----|                                 |
|                                               |
|                                               |
|-----------------------------------------------|



回答2:


Said another way: How far away is your peep hole from the top left corner. If you have a background position of -50, -20 that indicates that if you were to move the peep hole to be in the top left corner it would have to move left 50px (hence negative) and up 20px (hence also negative). So positioning is measure from the perspective of the peep hole and how its position is from the top left corner.




回答3:


http://www.alistapart.com/articles/sprites

Do you have firebug? http://getfirebug.com

If so, just inspect one of the elements with the sprite background and change the background position to 0 0. Then just start playing around with the positioning and you should be able to figure out how it works.

background-position: 0 0; means put the background image 0 pixels from the left and 0 pixels from the top.

background-position: 0 -50px; means put the background image 0 pixels from the left border, and 50 pixels above the top border, effectively moving the background image up 50 pixels. Try it out on your own using firebug or just changing the stylesheet and refreshing to see the effects.



来源:https://stackoverflow.com/questions/5365061/css-sprite-with-negative-background-positions-not-clear

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