The Complete WebDeveloper (38 Blogs) Become a Certified Professional

How to Implement CSS Sprites to Enhance Web-Pages

Published on Aug 29,2019 31 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

The concept of sprites has been around for a while now. It is one of the most commonly used techniques in the game industry to speed up the process of displaying animations on a screen. In this article, we will particularly look at how this technique can help us improve user experience on web pages with the help of CSS Sprites in the following order:

 

What is a Sprite?

A sprite is a single image that is part of a bigger scene in a game. Multiple sprites are then combined into a big image called a sprite sheet. Once a sprite sheet is loaded into the memory, different sprites are rendered in quick succession to give the illusion of animation. This is done simultaneously for tens to hundreds of different sprites to generate a scene in the game.

CSS Sprites

The basic idea is that it is much faster to load an image and display a part of it wherever required as compared to loading multiple images and display them.

 

What is CSS Sprite : A quick overview?

A CSS sprite is a technique which is often used by web developers to optimize the performance of web pages. In this technique, multiple smaller images usually of same dimensions are combined into a single big image called a sprite sheet or tile set. This sprite sheet is then used to display individual elements wherever we need them.

Usually, elements like logos, navigation arrows, buttons are included in the sprite sheet as they are almost of the same dimensions and are frequently used in a web page.

 

Example of how it helps in Web Development?

Generally, while designing web pages images are stored and used as individual files. So, when a user opens a webpage, the browser has to make an HTTP request for each of these files, download them separately and display them. This leads to higher page load times as a particular web page can have a large number of smaller images like buttons, icons, logos.

How Sprites Helps

CSS sprites help the developers to combine these frequently used small images into one big image. The browser then has to download only one file which is then used to display the required section by offsetting the image.

 

Advantages Of Using CSS Sprites

There are two main advantages of using CSS sprites over normal images:

  • Faster page loading:  Enhances the page loading time as images used in the web page appear as soon as the sheet is downloaded.

  • Greater throughput and lower resource usage: Not only this technique improves the end-user experience by making the page load faster, but it also reduces network congestion as lower number of HTTP requests are made.

 

What a Developer has to do when working with CSS Sprites?

When working with individual images, the developer can simply work with HTML tag <img> and style it in CSS if required. But when working with CSS Sprites, a developer needs to do two specific things:

  • Creation of Sprite Sheet

While developing a web page if the developer decides to use CSS sprites, he/she has to first create the sprite sheet by merging all the desired elements like buttons, logos, etc. in a grid-like pattern. This can be done using any image editing program like Photoshop or Gimp. There are also many online tools available that help you make the sprite sheet. These tools are discussed later in this article.

  • Access a particular element of the sprite using the CSS background-position property

Once the sprite sheet is ready, the developer then has to use CSS attributes to access different parts of the sheet.

  • width: Width of the sprite
  • height: Height of the sprite
  • background: Reference to the sprite sheet
  • Background-position: Offset values (in pixels) to access only the required part of the sprite sheet

 

How to create a CSS Sprite Sheet?

You can use any image editing software to arrange your smaller images into a grid but two easier methods are discussed below:

1. Online Sprite Sheet Creation Tool

LINK: toptal.com/developers/css/sprite-generator/

Online sprite sheet creation tool

This tool is not only free to use but also provides you with the required CSS code that can be used while referencing the sprite sheet. Also, you can fiddle around with different properties like padding between the elements and changing their alignment.

 

2. Generating Sprite Sheet with Sprity

If you are using Grunt, Node or Gulp, you can install a package called Sprity which will help you create a sprite sheet in a variety of formats like PNG, JPG, etc.

Firstly, you will need to install Sprity using:

npm install sprity -g

Then, to generate sprite sheet, use the following command:

sprity ./output-directory/ ./input-directory/*.png

 

How to work with CSS Sprites?

In this example, we will be using the following sprite sheet:

work with Sprites

As you can see in the above image six icons (Instagram, Twitter, and Facebook) have been arranged in a grid-like pattern. In the first row, we have a normal state and in the second row, we have their hover state (the image that appears once we hover the mouse cursor on them).

If you made the sprite sheet using the tools we discussed above then you already know the offsets required in the CSS but if you used some other tool or you were simply given some sprite sheet then don’t worry, we will be discussing a method that will help you get offsets for the required element.

Lets now see a very simple way to get required offsets for each of the six icons by using MS Paint. It may not be an ideal solution to work with sprites but since it has the feature that provides the coordinates of the mouse cursor, it can be used to get the required X and Y coordinates.

First, open your sprite sheet image (grid containing all the smaller images) and bring your mouse cursor on the top-left corner of the sprite that you want to grab.

grid

Once you have the coordinates of the top-left point of your sprite (top left Instagram image), you can display this specific sprite wherever required using the CSS code:

background: url('img_sprites.png');
background-position:0 0;
width: 125px;
height: 125px;

We are using width and height as 125 pixels as our icons are of that dimension. To fetch the next image (Twitter) in the same row, we use the following code:

background: url('img_sprites.png');
background-position:-128px 0px;
width: 125px;
height: 125px;

Note the background-position attribute in the above snippet. (-128px, 0) means we are offsetting our sprite sheet to the left by 128 pixels (taking padding between elements into account) and 0 pixels on the Y-Axis. If we were to access the twitter hover icon then our background-position attribute would be:

background-position:-128px -128px;

In this way, we can now access each component of our sprite sheet using CSS. Let’s go through a complete HTML and CSS code on how to do it.

 

Step 1: Writing the required HTML Code

In the below code, we are simply adding three links. Also, we will link our HTML with the stylesheet (screen.css).

 <span class="instagram icon"><a href="#">Instagram</a></span>

 <span class="twitter icon"><a href="#">Twitter</a></span>

 <span class="facebook icon"><a href="#">Facebook</a></span>

 

Step 2: Writing the necessary CSS. First, we will style our shared icon class. Here, you can see we are referencing to the sprite sheet that we created.

/* Shared icon Class */

span.icon a:link,

span.icon a:visited {

  display: block;

  text-indent: -9999px;

  background-image: url(./img_sprites.png);

  background-repeat: no-repeat;

}

 

Step 3: Getting the individual icons from the sprite sheet using the offsets.

/* Instagram Icon */

span.instagram a:link,

span.instagram a:visited {

  width: 125px;

  height: 125px;

  background-position: 0 0;

}

 

/* Twitter Icon */

span.twitter a:link,

span.twitter a:visited {

  width: 125px;

  height: 125px;

  background-position: -128px 0;

}

 

/* Facebook Icon */

span.facebook a:link,

span.facebook a:visited {

  width: 125px;

  height: 125px;

  background-position: -257px 0;

}

 

Step 4: Getting the hover icons from the sprite sheet using the offsets.

span.instagram a:hover {background-position: 0 -128px;}

span.twitter a:hover {background-position: -128px -128px;}

span.facebook a:hover {background-position: -255px -128px;}

 

 

Companies using CSS Sprites

Many big names in the industry use CSS Sprites to improve the responsiveness of their websites. Companies like Google, Facebook, Amazon extensively use this method as this helps them to reduce the number of HTTP requests per session for a particular user. This is a huge benefit when we take into account that these companies serve millions of customers at any given moment.

Now that you have a grip on what CSS sprites are and how to work with them, you are one step closer on your journey to learn CSS. Concepts like sprites are a game-changer in today’s time as it has become extremely important for developers to extract every bit of performance from a webpage.

Check out our Full Stack Web Developer Masters Program which comes with instructor-led live training and real-life project experience. This training makes you proficient in skills to work with back-end and front-end web technologies. It includes training on Web Development, jQuery, Angular, NodeJS, ExpressJS, and MongoDB.

Got a question for us? Please mention it in the comments section of “HTML Images” blog and we will get back to you.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.