Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've read every single question about responsive sprites using css, I saw jsfiddle with working examples of responsive sprites, but I still cannot understand how to get the percentage of background-position and of background-size, how to use a wrapper (some people say it is necessary) around the div that uses background-image and why to use it...
For instance, if I have a div that has width:20% (say 40px) and is a circle. The image I need to use as background-image has 80px width (a circle, and I need to resize it to fit my div) and is one of the 40 images I have in my sprite sheet. It is at the position -173px -293px.
I really have no clue how to make it work.
I tried:

div {
  width:20%;
  border-radius:50%;
  background: url('images/sprites.png') no-repeat 72.083% 67.981%;
  background-size: 50%;
  }

Of course, it did not work. I don't understand how to get the background-position-x, background-position-y (the numbers I have are from the "auto" size sprite sheet) when the background-size is not auto, or how the background-size relates to the percentage of the div size.
Is there any mathematical formula that I can use? Can anyone please explain me or give me a name of some website/book where I can learn it?
Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
379 views
Welcome To Ask or Share your Answers For Others

1 Answer

An update to @vals' answer. Some of his calcs didn't quite work for me.

The background-size calcs worked, except that he was multiplying by 1000 instead of 100 to get the final percentage figures. So 12500% should be 1250% and so on. (Update: 10/2015 - it looks like @vals has corrected this in his answer.)

The background-position X value calcs were very slightly out for me. They didn't match what was generated by spritecow.com (as per Adrian Florescu's suggestion). This is, I think, because absolute coordinates are calculated from the left of the background image, whereas with percentages, you have to calculate from the right of the background image. That being the case, you have to subtract the image width from the overall background width before you divide the absolute x-pos number with it.

So instead of:

x-part 173px / 1000px = 0.173 ->> 17.3%

do this:

x-part 173px / (1000px - 80px) = 0.1880434783 ->> 18.80434783%

Where:

1000px is the width of the background image (sprite)

80px is the width of displayed image

173px is the absolute x-coordinate of the displayed image.

This is what works for me, anyway!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...