Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image from sprite using CSS

Tags:

I have a CSS sprite with various icons in size 32x32px.

Now what I need is to display one of those icons in 20x20px size. I tried a few things, like setting the size to 20px, using background-size:cover, or using transform:scale(0.625) - but none of my attempts give the result I desire.

HTML for my tests:

32px icons:

<div class="sprite" style="background-position:0px 32px;">&nbsp;</div>
<div class="sprite" style="background-position:64px 32px;">&nbsp;</div>
<div class="sprite" style="background-position:32px 96px;">&nbsp;</div>
<div class="sprite" style="background-position:0px 0px;">&nbsp;</div>
<div class="sprite" style="background-position:32px 64px;">&nbsp;</div>

<hr>
20px icons (attempts):

<div class="sprite" style="background-position:32px 64px; width:20px; height:20px;">&nbsp;</div>
<div class="sprite" style="background-position:32px 64px; width:20px; height:20px; background-size:cover;">&nbsp;</div>
<div class="sprite" style="background-position:32px 64px; width:20px; height:20px; transform:scale(0.625);">&nbsp;</div>

CSS for my tests:

.sprite {
  background-image:url(http://buildnewgames.com/assets/article//dom-sprites/spritesheet.png);
  width:32px;
  height:32px;
}

Please have a look at this fiddle to see what I tried:

https://jsfiddle.net/dfqh0yrc/4/

like image 524
pimeys Avatar asked Dec 15 '16 06:12

pimeys


1 Answers

You can only use the scale without width and height like the following:

.sprite {
  background:url(http://buildnewgames.com/assets/article//dom-sprites/spritesheet.png);
  width:32px;
  height:32px;
}
32px icons:
<div class="sprite" style="background-position:0px 32px;">&nbsp;</div>
<div class="sprite" style="background-position:64px 32px;">&nbsp;</div>
<div class="sprite" style="background-position:32px 96px;">&nbsp;</div>
<div class="sprite" style="background-position:0px 0px;">&nbsp;</div>
<div class="sprite" style="background-position:32px 64px;">&nbsp;</div>
<hr>
20px icons (attempts):
<div class="sprite" style="background-position:32px 64px; transform:scale(0.625);">&nbsp;</div>
<div class="sprite" style="background-position:32px 64px; transform:scale(calc(20 / 32));">&nbsp;</div>

You can also use calc to calculate the scale factor like the following:

<div class="sprite" style="background-position:32px 64px; transform:scale(calc(20 / 32));">&nbsp;</div>

Demo on JSFiddle: https://jsfiddle.net/dfqh0yrc/5/

like image 79
Sebastian Brosch Avatar answered Sep 26 '22 16:09

Sebastian Brosch