Tuesday, August 13, 2013

CSS Sprites with Background Positioning

CSS Sprites with Background Positioning

There's nothing more common than hover states to give your website some life. The user comes to your site, scrolls over an image with their mouse cursor and the image changes. That's it. While I spent most of 2012 learning backend programming with Ruby on Rails, I'm only recently spending more time improving my frontend development skills. Earlier this week, I needed to implement the hover state effect so I researched what the best practice was. All of the tutorials and tips I could find were unclear, outdated, or plain confusing so I decided I'd write my own.

We're currently in development on some new things for Uncover and on one page we have an image that we want to change when a user rolls their mouse cursor over it. Here's the image:

CSS Sprites with Background Positioning

When a user rolls over it, we want it to change to this:

CSS Sprites with Background Positioning

Let's look at how I implemented this earlier today. I wanted to use what's known as Image Sprites in CSS. That's a collection of images on a single image, which helps reduce load times as the user only needs to make a single request to the server rather than multiple requests for each image.

Here's a look at the sprite I created:

CSS Sprites with Background Positioning

You can see that I have one image neatly aligned on top of the other. Both images are the same height and width.

In my example, I want the user to be able to click the image to go to a new page of the website. Note that it's just a standard HTML link with a class of preview.

Here's the CSS that goes along with the HTML:

.preview {
    display: block;
    margin: 0px auto 20px;
    width: 305px; height: 321px;
    background: image-url("preview-3.png") 0 0 no-repeat;
}

.preview:hover { background-position: 0 -321px; }

How this works is that the image on top is the image I want to display before hover. That's why the background is set to top. Then on hover I want the image below to be displayed, so that's why the background-position is set to bottom. It's that simple.