Search code examples
cssbackground-imagesprite-sheet

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


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

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


Solution

  • 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.sstatic.net/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.sstatic.net/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>

    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.sstatic.net/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>