Button with CSS Image Sprites

The button is one of the most common elements in HTML programming. Buttons are very useful when it comes to visual aids, they draw the user’s attention to important elements on the page. The button I am going to teach you how to create will have three different states: 1) static, 2) on hover, and 3) on click. The tutorial is as follows:

1) First to do this you will need to create an image. Use this image two create two more copies of the original image. Edit these so that they all have varying colors. I have provided three images below as an example. (Note: it is helpful to make all the images the exact same size).

Hover Static Click

2) Open your favorite XHTML editor and lets create  button. We will be using a simple anchor. Being an inline element, we’ll contain it within a block element of a paragraph, and give it a class to allow us to target it with the CSS we will be writing. Type the following code into your editor:

<p><a href=”#”>Press it</a></p>

3) The next step is to add the CSS. The first step is to change the anchor from its default state of inline element to block. This will then allow us to specify a width and a height. Copy and paste the given CSS below:

#demo p a.press-it-btn {
	display: block; 
	width: 433px; height: 174px; 
	background-image: url(button-sprite.png); 
	background-position: top; 
	text-indent: -9999px; 
}

4) Now we need to add the on-hover effect and the on-active affect. The following code will do this for you.

#demo p a.press-it-btn:hover {
	background-position: center; 
}
#demo p a.press-it-btn:active {
	background-position: bottom;
}

5) Finally, a little extra clean up is needed. Add these last lines to your CSSand your done.

a { outline: none; }
#demo p a.press-it-btn:hover, #demo p a.press-it-btn:focus

And that’s it. Give it a try. Your button will now change its image based upon whether its NOT being clicked/hovered, it IS being hovered or clicked. Three different states. Pretty cool.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s