Optimizing images with CSS icon sprites

 

Choosing the right icons

There are many choices for icons available in 2020. We can easily incorporate icons from FontAwesome, Material UI and other React based user interfaces. We should always reach for these first when it is an option. Often, however, we want to customize things for our clients. For these cases we use CSS icon "sprites".

We want to take advantage of the idea of loading multiple resources while minimizing network traffic to do it, similar to how there are multiple graphics in one FontAwesome font file. Fortunately, modern CSS makes this very easy, if perhaps a little bit verbose. We borrow a term from game development here, and we'll call the resulting CSS icon a "sprite". Our sprites will have multiple states for hovering and clicking or touching, and we will include all images and states in one file.

CSS icon gridPreparation

What we need to do first is very straightforward. Make a regular shaped grid in a graphics file and pack multiple icon images into each square of the grid. The resulting file can be loaded in one request by the browser, and then cached for subsequent page visits. We chose SVG format for our client Mona Caron, since the resulting file size came out smallest when compared against PNG or JPEG. The Adobe Illustrator template attached to this post is arranged for square 50x50 graphics, but there is no requirement here that the icons be square. A tall or wide shape is fine, as long as it is consistent for the entire grid.

CSS code

Once we have the graphics grid, the following CSS ties everything together.

.icon {
  display: inline-block;
  overflow: hidden;
  background-image: url(
/path/to/sprites.svg);
  background-repeat: none;
  text-indent: 10000px;

  width: 50px;
  height: 50px;
}

.icon.facebook { background-position: -100px 0; }
.icon.facebook:hover { background-position: -100px -50px; }
.icon.facebook:active { background-position: -100px -100px; }
/* ... repeated for each sprite ... */

The positions in the grid are encoded into the background-position CSS property. The values are negative because we are shifting the image up and left from the (0, 0) origin. A background-position value of 0 0 would show the icon in the upper left corner of the grid image.

HTML code

Now to include this in our HTML we can write.

<i class="icon facebook"></i>

This will add a 50x50 Facebook icon to our page with hover and click states.

CSS icon results in practice

We have reduced the number of server connections here from twelve to one, a 91.6% reduction of traffic.

This can translate to a significant significant time savings for people with limited bandwidth or on mobile devices.

Let's discuss:  SlackFacebook, or  Twitter.