What Is Sprite Generation?
Sprites are an important way to improve user experience and website performance by reducing network overhead and the number of downloaded files on web pages. A sprite is a single image that contains a set of images. The browser downloads a single sprite image, and CSS code gives the browser the coordinates of each image in the sprite, allowing them to be displayed separately.
This is part of a series of articles about Website performance.
In this article:
- Why Use CSS Sprites?
- Should the Sprites Be Horizontal or Vertical?
- Implementing Image Sprites Manually in CSS
- Generating Sprites Using Automated Tools
Why Use CSS Sprites?
CSS sprites are a way to reduce the number of HTTP requests to image resources referenced by your site. The images are combined into one large image, and each individual image has defined X and Y coordinates. You can then use the background-position CSS property to move the viewport to the desired component image.
This technique is very effective in improving website performance, especially for small images such as menu icons.
The only downside to using CSS sprites is that they don’t work consistently across all browsers. Specifically, they are well supported by Chrome and Firefox, while support is more limited on older versions of Internet Explorer and Opera. If you don’t need to support older browsers, you can provide cross-browser compatibility for most modern browsers with just a few CSS modifications.
Related content: Read our guide to website speed
Should the Sprites Be Horizontal or Vertical?
Sprites do not have to be horizontal or vertical. It is possible to compact a sprite into a grid to make it as small as possible. An image’s dimensions impact the amount of memory it consumes during use, so the smaller, the better. If you choose to lay out custom sprites, you can use Sprite Cow to help you generate the CSS code.
You may choose to pick one dimension for simplicity. In this case, what matters is not whether you choose the horizontal or vertical dimension but the maximum size of the image.
For example, consider the largest height and width of the image files to determine which is greater. If the height dimension is larger, you should arrange the sprite sheet vertically, but you should arrange it horizontally if the width dimension is larger. If you use a sprite generation tool, it will likely do this automatically.
In some cases, you might want to lay out sprites diagonally to enable the use of the sprites in areas with unknown width or height dimensions.
Implementing Image Sprites Manually in CSS
CSS provides a simple way to implement image sprites. The technique is to create one image with multiple smaller images arranged in a grid. You can then set the image as the background of a CSS class.
For example, consider this .icons class, which has the image icons.png as its background. This image has icons arranged in 30x30px cells.
.icons { background: url(icons.png); display: inline-block; height: 30px; width: 30px; }
Now we define two elements with ID , icon1 and icon2 (the elements will need to have the icons class assigned to them).
We can then use the background-position property to move the icons.png image so that the correct icon is shown. For one icon, we set a background position of (-30,0), and for the second one, we set the position to (-60,0). In this way, you can handle a sprite with a large number of icons or other images.
#icon1 { background-position: -30px 0px; } #icon2 { background-position: -60px 0px; }
You can also set a hover position. For example, if you want to show the third icon in the grid (with offset -90px) when the icon1 element is hovered, you can use code like this:
#icon1:hover { background-position: -90px 0px; }
Generating Sprites Using Automated Tools
Here are some of the tools you can use for automatic sprite generation:
Sprity
If you use Grunt, Gulp, or Node to generate sprites, you can leverage sprity, a node package, for creating sprites from clusters of images. Sprity offers several features, including:
- JPG, PNG, or Data URI output formatting
- CSS, Sass, Stylus, and LESS stylesheet generation
Install CCS-Sprite across all systems to compile sprites using the following command-line script:
$ npm install sprity -g
You can then create sprites and a corresponding stylesheet by running the following:
$ sprity ./output-directory/ ./input-directory/*.png
Compass
Using Compass to generate sprites requires a few additional configuration and maintenance steps. If you already use Compass, it may integrate well with your established workflow.
First, create a sub-directory in your image directory—it must be within the directory labeled “images” to work. Name it according to the type of sprites you want to generate. For example, if you choose to generate flag sprites, you might name your directory “flags.” Make sure the images converted to sprites are in PNG format before you put them in the new directory.
Create a new SCSS file with a corresponding name, such as “flags.scss” for the flag sprite example. The following lines will import sprite creation tools from Compass, import the PNG files for conversion, and generate the CSS code for all the sprites:
@import "compass/utilities/sprites";
@import "flags/*.png";
@include all-flags-sprites;
Note that the order of the commands is important. The middle word in the statement following @include must match the preceding directory name in the @import statement (in this case, “flags”).
It is relatively simple to generate sprites using this process, but it also has drawbacks, including the lack of heights and widths in the generated CSS. Also, the sprites do not have a shared class, so it applies the background image to every class.
ImageMagick
You can use ImageMagick to create sprite sheets via the command line using these commands:
convert *.png -append sprites.png # append vertically
convert *.png +append sprites.png # append horizontally
These commands concatenate all the PNGs that the glob selects to generate a single file. However, this method does not generate a corresponding style sheet.
Cloudinary
Cloudinary Programmable Media is a cloud-based image management solution with a generous free plan. You can upload a group of images to Cloudinary, giving them a common tag, and generate sprite images and the corresponding CSS files automatically.
The difference between Cloudinary and the other tools we covered above is that Cloudinary handles the whole process from end to end. It lets you upload your images, define the sprite, and deliver it to users over a fast CDN.
Step 1: Upload images
Create a free account, upload images and assign tags to them using the Cloudinary Management Console or the Upload API.
For example, you can upload a set of corporate logos to Cloudinary and give them the tag ‘sprite_logo’.
Step 2: Auto-generate the sprite
The sprite and corresponding CSS code is automatically generated when you deliver a dynamic sprite URL, which looks like this:
https://res.cloudinary.com/demo/image/sprite/sprite_logo.png
This one line of code generates the sprite on demand when accessed for the first time (up to 100 images).
We uploaded four logos to our demo account with the public IDs: amazon_logo, apple_logo, microsoft_logo and google_logo and assigned the tag sprite_logo to all of them. Now the above URL generates the following image:
Step 3: Add CSS code to your HTML page
To use the sprite in your HTML code, you need to reference the generated CSS of the sprite, which has the same URL as the sprite image, but with the .css extension, like this:
https://res.cloudinary.com/demo/image/sprite/logo.css .amazon_logo, .apple_logo, .google_logo, .microsoft_logo { background: url('//res.cloudinary.com/demo/image/sprite/v1630230323/sprite_logo.png') no-repeat; } .amazon_logo { background-position: 0px 0px; width: 162px; height: 38px; } .apple_logo { background-position: 0px -40px; width: 206px; height: 250px; } .google_logo { background-position: 0px -292px; width: 275px; height: 95px; } .microsoft_logo { background-position: 0px -389px; width: 216px; height: 70px; }
The generated CSS and PNG files are automatically distributed through a CDN and smartly cached. Note that both the image and css of the sprite will be generated if they don’t exist, whether you access the ‘.png’ URL or the ‘.css’ URL.
Step 4: Display a specific image from the sprite
To display an image from your sprite, include the CSS in your page and use the relevant style class name. For example, to display the Amazon logo, use the following HTML code:
<link rel="stylesheet" type="text/css" href="https://res.cloudinary.com/demo/image/sprite/sprite_logo.css"> ... ... <div class="amazon_logo"></div>