问题描述
.my-sprite {
background-image: url("https://i.stack.imgur.com/lJpW8.png");
height: 100px;
width: 100px;
background-position: 0 0;
background-position: -200px 0px;
}
<div class="my-sprite"></div>
我无法将子画面缩放到较小的尺寸.我希望它是实际大小的一半,即100x100px,如何使用background-size
属性缩放它?现在,它仅显示100x100px的完整图片大小...
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...
推荐答案
您的图片精灵的尺寸为500x400,因此,如果要在background-size
上减小2,请定义此尺寸的一半,然后调整background-position
以获得您想要的任何图标:
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/lJpW8.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/lJpW8.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>
这是一个通用公式,使用CSS变量表示刻度编号以及选择图标.
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/lJpW8.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>
这篇关于用作背景图像时如何缩放CSS精灵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!