Web Performance Exploring Video Hosting The Art of Compromise: How Lossy Compression Works Understanding the ‘Image Loading Error’: Comprehensive Guide A Comprehensive Guide to Resizing Images on iOS VBR vs CBR: Understanding Bitrate for Optimal Media Handling Displaying Images with Python’s Top 5 Image Libraries 4 Ways to Add Images to GitHub README + 1 Bonus Method Converting Images with Python JavaScript Image Optimization Techniques Building an Image Picker in React with react-native-image-crop-picker 6 Ways to Save Images in Python 5 Ways to Import Images in React + Bonus Automation Method Extract Text from Images in Python with Pillow and pytesseract Downloading Image from URL in Python: 5 Ways with Code Examples Image.open Python Function: Syntax and Quick Tutorial Complete Guide to Video SEO & Automating It With Cloudinary A Complete Guide To Website Image Optimization Video Encoding: How It Works, Formats & Best Practices The Developer’s Guide to PDFs Integrating Cloudinary With Gatsby For Image Optimization Mastering Image Optimization With Netlify And Cloudinary Seamlessly Integrate Cloudinary With Netlify For Optimised Website Assets Ultimate Guide to Asset Optimization Using Cloudinary and Netlify Adding Video To Magento Understanding Magento Media Adding a Video Widget to Your Website: What You Need to Know SDR vs. HDR: Differences and 5 Considerations for Content Creators Audio Manipulation In PHP Image Management Systems: Key Capabilities and Best Practices Video CDN: Why You Need It and Top 5 Video CDNs Video Optimization: Why You Need It and 5 Critical Best Practices Multi CDN: 8 Amazing Benefits, Methods, and Best Practices What Is an Optimized Website and 6 Ways to Optimize Yours Understanding Image Hosting for Websites Sprite Generation with CSS and 4 Automated Tools 8 Image SEO Optimization Tips to Improve Your Search Rankings Website Speed: 5 Reasons Your Site is Slow and How to Fix It Web Performance: What is it, Trends and Insights for 2024

Sprite Generation with CSS and 4 Automated Tools

css sprite generation

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?

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>
QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you optimize CSS sprite generation for your website:

  1. Group images by usage context
    Organize images that are used in the same context (e.g., navigation icons or social media logos) into a single sprite. This ensures faster loading and avoids unnecessary loading of sprites containing unrelated images, improving both performance and usability.
  2. Compress sprites without losing quality
    Use lossless compression tools like ImageOptim or TinyPNG to reduce sprite file sizes without degrading image quality. This minimizes bandwidth usage and accelerates page load times, especially for mobile users on slower connections.
  3. Combine sprites with lazy loading
    For pages with many assets, consider combining sprite generation with lazy loading techniques. This way, non-critical sprites are loaded only when needed, reducing initial page load time and improving performance metrics like Time to First Byte (TTFB).
  4. Use retina-ready sprites for high-resolution displays
    Create 2x resolution sprites for high-DPI displays like Retina screens. Use media queries to serve these high-resolution sprites to devices that support them, ensuring sharp visuals without increasing file sizes for regular displays.
  5. Leverage sprite caching
    Configure your server or CDN to cache sprite images for longer durations. Since sprites typically contain icons or logos that change infrequently, caching helps reduce server load and speeds up page reloads for returning users.
  6. Automatically generate CSS classes
    When generating sprites, automate CSS class generation for easier integration. Tools like Cloudinary or Compass handle this by outputting background positions and dimensions for each image, saving you time and reducing errors when coding manually.
  7. Monitor and optimize sprite sheet size
    Keep sprite sizes manageable. Large sprites can still slow down loading times, especially if the sprite contains numerous or high-resolution images. Split large sprites into smaller logical groups when necessary to maintain optimal performance.
  8. Update sprites incrementally
    When adding or removing icons from a sprite, avoid regenerating the entire sheet from scratch. Instead, append new icons to the existing sprite to preserve caching and minimize the need for users to download an entirely new file.
Last updated: Aug 24, 2024