Image Rollovers with CSS

A easy way to create interactive features on a website is the simple rollover. A common device for revealing information or making links or a call-to-action more enticing and clickable, the rollover is used in a variety of ways. First we’ll be looking at how to create a simple text rollover using CSS.

1. The simple Text rollover

The first thing we’ll need to do to make some text have a rollover effect is make it a link. Contain your text within an A tag, like this:

 my link

If the element you’d like to make a rollover isn’t supposed to link to anything in particular put a # sign into the href part of your a tag. Next we’ll make a CSS style for that link:

a {
   color: #FFF;
   background-color: #000;
   padding: 5px;
}

Then we’ll add a new CSS style for the hover state (when a rollover occurs).

a:hover {
   background-color: #C00;
}

2. Buttons from a Unordered List

Another common practice is to use a list as a way to structure your navigation items. Normally we use an unordered list tag to create this:


Now let’s add some CSS to make those act more like buttons:

		ul {
			list-style: none;
		}

		li {
			padding: 10px;
			margin: 0px;
			width: 200px;
			height: 20px;
		}

		ul a {
			background-color: #C00;
			display: block;
		}

		ul a:hover {
			background-color: #000;
		}

Image in Background

So far so good, next we’d like to replace the plain background colour with an image. I’ve prepared an image in Photoshop with some texture that combines both the “default”(non-rollover) state and the rollover state into a single image, both images adjacently placed one underneath the other. Here’s what I mean:

Here’s the actual image:

And here’s the CSS to use to bring that image into both the default and rollover states:

		ul #buttons {
			list-style: none;
		}
		li {
			padding: 10px;
			margin: 0px;
			width: 200px;
			height: 20px;
		}
		#buttons a {
			background-image: url("button-rollover.gif");
			display: block;
		}
		#buttons a:hover {
			background-position: 0 -30px;
		}

Here’s a ZIP file of the HTML, CSS and image files for this example.
Download Example files

Other CSS Tutorials

Image Rollovers with CSS
http://www.creativepro.com/article/view-source-advanced-css-rollovers

Speckyboy
http://speckyboy.com/2009/05/27/22-css-button-styling-tutorials-and-techniques/

Smashing Magazine:
http://coding.smashingmagazine.com/2010/02/18/50-css-and-javascript-techniques-for-layouts-forms-and-visual-effects/


Posted

in

by

Tags:

Comments

Leave a Reply