Spriting with <img>

Published by Robin Rendle

Sprites aren't limited to background-image, as with the object-fit and object-position properties we can nudge an inline image around its content-box to act just like a sprite. For example, let's say we want the image below to be added to our HTML page like a regular ol' image:


Sprite
<img src='sprite.png' alt='Icons'> 

Then we'll crop the image so that only the first icon is visible on screen:

img {
  object-fit: none;
  object-position: 0 0;
  width: 100px;
  height: 100px;
}

Sprite image cropped to reveal the world icon

Here, the content-box of the <img> should be 100px wide and 100px tall, but because the image extends beyond those boundaries, it's automatically cropped for us with object-fit: none. We might then want to use a class to nudge the image and reveal another part of it altogether:

.book {
  object-position: 0 -234px;
}

Sprite cropped to reveal the book icon

These sprites can be in any regular image format but it's also possible to use the same technique with SVG. Here's an example that currently works in the latest stable version of Chrome:

See the Pen Sprites with object-position by Robin Rendle (@robinrendle) on CodePen.

Image Slider

Using a dab of JavaScript, we can actually use this same concept to create an image slider out of a single <img> tag. When the image is clicked, just change some classes which change the object-position.

See the Pen SVG sprite with object-position by Robin Rendle (@robinrendle) on CodePen.

Support

Keep this in mind for the future, since unfortunately the browser support for object-fit isn't particularly great at the moment. The current desktop versions of Safari and Firefox don't support it and neither does iOS. So make sure to double check the almanac entry for object-fit before using this trick anytime soon.