Using image sprites with CSS on your website can be extremely useful in decreasing load times on your website and also avoiding flickering upon hover that is often associated with using separate images. But what if your site needs to be responsive? Using a clever bit of code, we can make the background image of a div a sprite that will still work in a responsive design.

Basically all we have to do is apply a class to a div that we want to use. The background of this div will be our CSS sprite. Here would be the code:

div.sprite {

width: 20%;
height: 0;
padding-bottom: 20%;
background-image: url("images/ourimage.png");
background-position: 0 0;
background-size: 200%;
display:block;

}

A bit of this code allows the div to maintain its aspect ratio in a responsive design, and then the background image resizes to fill it in. We determine the ratio based on the ratio of the image we are trying to display. You can find out more about maintaining the aspect ratio of an element with css here.

Then we just need to add the last bit of code to change the image in the hover state. All we need to add is this:

div.sprite:hover {

background-position: 100% 0; /* Use ONLY percents here */

}

Voila! That’s all you need. Note, this may not work quite right in IE8 or earlier. Everything will display, but your images won’t be the correct size most likely. Let me know if you need any more help!

Advertisements