Blog

Personal thoughts, tutorials and more...

Using Sprite Images and Their Advantages

Using Sprite Images and Their Advantages

So you have a button and it has a hover effect. Doesn’t matter whether its a glow effect or the button just changes completely, you have 2 CSS solutions to show the on hover effect. But which one should you use? And what are the advantages and disadvantages for them? Your about to find out.

So what are the best ways you can do this? Well you whatever it is your gonna use the hover pseudo class in CSS. So lets go over the techniques and figure out which one is the best.

The first one is using a sprite image. Basically you will have both the mouse over and mouse out images on one single image. Observe the following image.

Here is the HTML code:

  <div id="myButton"></div>

Here is the CSS:

#myButton
{
  width: 92px;
  height: 34px;
  background: url('images/my-button.png') top left no-repeat;
}
#myButton:hover
{
  background-position: 0 -34px;
}

Demo 1

As you can see we have a nice little mouse over effect for our button. So what are the advantages of using this effect? Using sprite images is almost like preloading your images before hovering. You probably didn’t notice that there was no load time to bring in the second image. Thats because there is none its all in one image. I will show you what I mean by showing you a second way of doing the same effect.

For the second way of doing this trick, we will need to separate the image into 2. As Shown Below.

my-button.png

my-button-hover.png

Here is the HTML code:

  <div id="myButton"></div>

Here is the CSS:

#myButton
{
  width: 92px;
  height: 34px;
  background: url('images/my-button.png') top left no-repeat;
}
#myButton:hover
{
  background: url('images/my-button-hover.png') top left no-repeat;
}

Demo 2

So this does the exact same thing as the other way but why would you choose one over the other. You may or may not notice this, depending on how fast your internet speed is, but with the second demonstration you may notice that the image kind of blinks, thats because the browser doesn’t load the second image until you mouse over the button. So there is a delay of a split second before the mouse over effect shows whereas in the first demo you load both images before there is a mouse over. The mouse over for the first demo only changes the position of the background image to emulate a change of image.

Another advantage for image sprites are that they help load the page faster. By loading only one image to your website you decrease the amount of HTTP requests your site has to make.

I hope this little tip helps you understand more of how you can take advantage of sprite imaging for hover effects.

Leave a Reply

back to top