CSS Button Sprites Tutorial

CSS sprites are pretty cool, not only do they save HTTP requests but you can also use them to build your own sprite framework. In this post I will show you how to implement the image of a two-state button into your design.

How Sprites Are Seen By CSS

CSS can interact with images using coordinates with the background property.

  • The top left corner is the coordinate (0 , 0)
  • To move the background to the left you would subtract from the X position e.g. ( -10, 0)
  • To move the background up you would subtract from the Y position e.g. (0,-10)

Take a look at this sign up button I made using Photoshop. The top button is its regular state, the bottom one is its active state.

Sign UP Button Sprite

You can apply background images to buttons and link the buttons to a page, unfortunately though, linking buttons doesn’t work in internet explorer which is why we use regular anchors instead.

Preparing Anchor Tags For Sprites

We will need to set the width and height of our link to the width and height of the buttons in the image. The only way you can change an <a>’s dimension is if its display property is set to block.

I will use a class called "button" for all anchors that can use the same sprite background. I will then add another class to change the background’s position.

a.button
{
background-image:url('buttons.png');
background-repeat:no-repeat;
display:block;
cursor:pointer;
text-indent:-9999px;
}

The text-indent property will make sure that the text inside the anchor tag is not shown.

Applying Different Sprites Accordingly

My signup button sprite is 305px by 75px, when it’s not active the background position must be set to (0,0)

Sprites for My Sign Up Button

a.signup
{
background-position:0px 0px;
width: 305px;
height: 75px;
}

When an user clicks on the button I want to move the background up so that the new background is the pressed button.

a:active.signup
{
background-position:0px -75px;
}

That’s all the CSS I need for my signup button. This is the HTML that will render the button.

<a class="signup button" href="#">Sign Up</a>

As you can see position sprites to CSS is not hard at all

blog comments powered by Disqus