responsive sprites / percentages

The div dimension doesn't play in the calculus, only the background sizes, and the part that you are going to use.

Lets say that your background has a width of 1000px and a height of 500px.

The image that you are going to use has 80px width and height.

background-size:

x part     1000px / 80px = 12.5   ->> 1250%
y part      500px / 80px = 6.25   ->>  625%

background-size: 1250% 625%;

background-position:

x-part     173px / 1000px = 0.173   ->> 17.3%
y part     293px / 500px = 0.586    ->> 58.6%

background-position: 17.3% 58.6%;

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!

Tags:

Css

Sprite