CSS Sprites

CSS sprites is a method where you take multiple images and combine them into one single image so that you can use to reduce the number of assets that are loaded when someone visits the webpage.  I don’t think that it does anything for the total download size of the images but it does reduce the number of assets that are loaded.  When I went looking for an example to show, I found a project on github that uses CSS sprites to show international flags.  Let’s take a looks at it.

See the Pen
CSS Sprites – Part 1
by Joe Steinbring (@steinbring)
on CodePen.

As you can see, this method sets the image as the background for the element and then uses a defined height and width and a background-position value in order to determine what part of the image to display.  The only downside of the above example is that you need to include more content than you probably need.

So, let’s try to do this from scratch.  I took a 54kb picture of my cat and a 63kb image of my dogs and combined them into a 763kb image that contains both pictures (somehow going WAY over the sizes of the individual images).

See the Pen
CSS Sprites – Part 2
by Joe Steinbring (@steinbring)
on CodePen.

As you can see above, implementation is fairly straightforward.  In fact, there is a web app that you can use to determine the coordinates necessary and generate your CSS classes.

Have a question, comment, etc?  Feel free to drop a comment, below.

 

[ Cover photo by Anthony Tran on Unsplash ]

Leave a Reply

Your email address will not be published. Required fields are marked *