How to scale CSS sprites when used as background-image?

会有一股神秘感。 提交于 2019-11-28 11:16:28

问题


.my-sprite {
  background-image: url("https://i.stack.imgur.com/TkysI.png");
  height: 100px;
  width: 100px;
  background-position: 0 0;
  background-position: -200px 0px;
}
<div class="my-sprite"></div>

I can not get my sprites to scale to a smaller dimension. I want it to be like half of the actual size which is 100x100px how can I scale it with background-size property? Right now it only shows the full image size of 100x100px...


回答1:


Your image sprite has a dimension of 500x400 so define half this size if you want to reduce by 2 on the background-size then adjust the background-position to get any icon you want:

.my-sprite {
    background-image: url("https://i.stack.imgur.com/TkysI.png");
    height:50px;
    width:50px;
    background-position:150px 0px;
    background-size:250px 200px;
    
    border:1px solid;
}
<div class="my-sprite"></div>

You can decrease more by any scale number, you simply need to do the correct calculation

.my-sprite {
    background-image: url("https://i.stack.imgur.com/TkysI.png");
    height:calc(100px / 5);
    width:calc(100px / 5);
    background-position:calc(3/5 * 100px) 0px;
    background-size:calc(500px / 5) calc(400px / 5);
    
    border:1px solid;
}
<div class="my-sprite"></div>

Here is a generic formula using CSS variables for the scale number and also for selecting the icon.

.my-sprite {
    --n:1; /* scaling factor */
    /* coordinates of the image */
    --i:3; 
    --j:0; 

    display:inline-block;
    background-image: url("https://i.stack.imgur.com/TkysI.png");
    height:calc(100px / var(--n));
    width:calc(100px / var(--n));
    background-position:calc(var(--i)/var(--n) * 100px) calc(var(--j)/var(--n) * 100px);
    background-size:calc(500px / var(--n)) calc(400px / var(--n));
    
    border:1px solid;
}
<div class="my-sprite"></div>
<div class="my-sprite" style="--n:2;--i:2;--j:2"></div>
<div class="my-sprite" style="--n:3;--i:4;--j:1"></div>
<div class="my-sprite" style="--n:4;--i:1"></div>
<div class="my-sprite" style="--n:5;--j:3"></div>
<div class="my-sprite" style="--n:0.5"></div>
<div class="my-sprite" style="--n:0.8"></div>



回答2:


You could use transform:scale().

.my-sprite {
  background-image: url("https://cdn.pbrd.co/images/HkKj0eC.png");
  height: 100px;
  width: 100px;
  background-position: -200px 0px;
  transform: scale(.3);
}
<div class="my-sprite"></div>


来源:https://stackoverflow.com/questions/50301190/how-to-scale-css-sprites-when-used-as-background-image

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