CSS sprites will not scale

2019-03-01 05:38发布

<div class="my-sprite"></div>

.my-sprite {
    background-image: url("https://cdn.pbrd.co/images/HkKj0eC.png");
    height:100px;
    width:100px;
    background-position: 0 0;
    background-position:-200px 0px;
}

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...

2条回答
叛逆
2楼-- · 2019-03-01 06:02

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://cdn.pbrd.co/images/HkKj0eC.png");
    height:50px;
    width:50px;
    background-position:-350px 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://cdn.pbrd.co/images/HkKj0eC.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 by using CSS variable for the scale number and also for selecting the icon.

.my-sprite {
    display:inline-block;
    background-image: url("https://cdn.pbrd.co/images/HkKj0eC.png");
    height:calc(100px / var(--n,1));
    width:calc(100px / var(--n,1));
    background-position:calc(var(--i,3)/var(--n,1) * 100px) calc(var(--j,0)/var(--n,1) * 100px);
    background-size:calc(500px / var(--n,1)) calc(400px / var(--n,1));
    
    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>

查看更多
3楼-- · 2019-03-01 06:08

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>

查看更多
登录 后发表回答