Sprite Generation with CSS and 4 Automated Tools (2024)

Sprite Generation with CSS and 4 Automated Tools (1)

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
    • Sprity
    • Compass
    • ImageMagick
    • Cloudinary

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:

Sprite Generation with CSS and 4 Automated Tools (2)

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>
Sprite Generation with CSS and 4 Automated Tools (2024)
Top Articles
Benefits of Forex Trading | Share India
Understanding Foreign Exchange Risk and How to Minimize It
Matgyn
Www.1Tamilmv.cafe
Txtvrfy Sheridan Wy
Athletic Squad With Poles Crossword
2022 Apple Trade P36
Big Y Digital Coupon App
True Statement About A Crown Dependency Crossword
Https://Gw.mybeacon.its.state.nc.us/App
Nier Automata Chapter Select Unlock
Aktuelle Fahrzeuge von Autohaus Schlögl GmbH & Co. KG in Traunreut
Socket Exception Dunkin
Lima Funeral Home Bristol Ri Obituaries
Apus.edu Login
Condogames Xyz Discord
V-Pay: Sicherheit, Kosten und Alternativen - BankingGeek
Beryl forecast to become an 'extremely dangerous' Category 4 hurricane
Katie Sigmond Hot Pics
Tripadvisor Napa Restaurants
Pasco Telestaff
Baldur's Gate 3: Should You Obey Vlaakith?
Jermiyah Pryear
Trivago Myrtle Beach Hotels
Pokemon Inflamed Red Cheats
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
10 Best Quotes From Venom (2018)
Lininii
Craig Woolard Net Worth
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Japanese Pokémon Cards vs English Pokémon Cards
Morlan Chevrolet Sikeston
Seymour Johnson AFB | MilitaryINSTALLATIONS
How Much Is Mink V3
SF bay area cars & trucks "chevrolet 50" - craigslist
Tedit Calamity
Home Auctions - Real Estate Auctions
VPN Free - Betternet Unlimited VPN Proxy - Chrome Web Store
Payrollservers.us Webclock
National Weather Service Richmond Va
Conan Exiles Tiger Cub Best Food
Spurs Basketball Reference
Who uses the Fandom Wiki anymore?
Food and Water Safety During Power Outages and Floods
Barback Salary in 2024: Comprehensive Guide | OysterLink
Mmastreams.com
Solving Quadratics All Methods Worksheet Answers
Unit 4 + 2 - Concrete and Clay: The Complete Recordings 1964-1969 - Album Review
Strange World Showtimes Near Century Federal Way
Varsity Competition Results 2022
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 5834

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.