This site is dedicated to all things I see and that I think are interesting to publish almost always are other very smart people.

Spriting with

Sprites aren’t limited to background-image, as with the object-fit and object-positionproperties 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-fitisn’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 forobject-fit before using this trick anytime soon.

Spriting with <img> is a post from CSS-Tricks

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s