Edgar C.
Edgar C.

Reputation: 1

Make CSS sprite image always fill its container

I've been struggling on this for quite a while now. I'm currently working on a project where I need to use a sprite from a sprite sheet as a button.

My sprite is 200x20, so if my button is the same width and height, there's no problem. But if my button is 400x20 (or any bigger size), it won't scale up. If my button is smaller, the image is just being cut (with a 100x20 button, the image is cut in half).

The thing is that I must use the same sprite for all these buttons, so it needs to scale up or down to fill its container, no matter what its size is, even is the aspect ratio is not kept. If it's not clear, the entire sprite must always fill all the space in the div (it should grow or shrink depending on the container's size).

I have tried using background-size with many different properties, but nothing seems to work. Transform: scale() is useful but it looks like it always keeps the aspect ratio, so I can't have half buttons for example.

.normal {
  width: 200px;
  height: 20px;
  /* The sprite is already 200x20 so this button is perfect.*/
}
.huge {
  width: 400px;
  height: 40px;
  /* The div is bigger than the first one, the sprite should scale and stretch if aspect ratio can't be maintained. */
}
.half {
  width: 100px;
  height: 20px;
  /* The right end of the div must be the sprite's end just like the first div. 
    So the image should not be cut in half, just resized even if aspect ratio is not kept.*/
}

.button {
  background: url("https://i.imgur.com/N75gIin.png");
  background-position: 0px -66px;
  background-repeat: no-repeat;
  image-rendering: pixelated;
}

.button:hover {
  background-position: 0px -86px;
}
<div class="button normal">Singleplayer</div>
<br><br>

<div class="button huge">Multiplayer</div>
<br><br>

<div class="button half">Settings</div>

The sprite sheet I'm trying to use.

enter image description here

I really hope someone will be able to help me, it seemed easier than it actually is.

Upvotes: 0

Views: 611

Answers (0)

Related Questions