sprites for icons with responsive size like `background-size: contain;`

869 views Asked by At

I have an app that has lots of icons. I know that using sprites for these icons is the correct way instead of having multiple small images. However, I needed those icons to be the same size as the container (background-size: contain;), so I was forced to use multiple images for each icon:

.icon1 {
  background-image: url('../my-site/icon1.gif');
  background-size: contain;
}

.icon2 {
  background-image: url('../my-site/icon2.gif');
  background-size: contain;
}
. . . and so on...

Using sprites however, would result to:

  1. (without background-size: contain;) - image is so small when i.e button is big

  2. (using background-size: contain;) - the whole sprite is being shown to the container!

Is there a way to use a responsive sprite that would show the icon (using background-position) and making that icon 100% width and height of container?

1

There are 1 answers

0
Ahmad Alfy On BEST ANSWER

There is no magic solution to achieve that sadly. You will have to adjust the size of the background itself manually.

#home {
    width: 46px;
    height: 44px;
    background: url(https://i.imgur.com/1ijjJJU.gif) 0 0;
}

#next {
    width: 43px;
    height: 44px;
    background: url(https://i.imgur.com/1ijjJJU.gif) -91px 0;
}

#home-double {
    width: 92px;
    height: 88px;
    background: url(https://i.imgur.com/1ijjJJU.gif) 0 0;
    background-size: 268px;
}

#next-double {
    width: 86px;
    height: 88px;
    background: url(https://i.imgur.com/1ijjJJU.gif) -182px 0;
    background-size: 268px;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>

<p>Normal size</p>
<p><img id="home" src="img_trans.gif"></p>
<p><img id="next" src="img_trans.gif"></p>

<p>Double size</p>
<p><img id="home-double" src="img_trans.gif"></p>
<p><img id="next-double" src="img_trans.gif"></p>

</body>
</html>

Note that with changing the background size you also have to change the background position.

Of course it is insane and doesn't make sense.

I recently stopped using sprite in favor of SVG sprites. They are incredible and more flexible and allow you to do much more. You can change their color and size, play well on retina screens.

If you still prefer PNG icons I would say ditch the sprites. Maintaining them is difficult even with a proper build process. Go for https and http2 then you will have absolutely zero problem with multiple concurrent requests.