I decided to bring this tutorial back from the grave since people seemed to like it. This one is pretty simple, we will just be walking through the nuances of the :hover selector in CSS.
This selector, like most styles, can be applied to absolutely any HTML element in your web page to create a rollover effect. A lot of people still use javascript to do this, which works but is deprecated. In other words, this is the ninja way to do things.
1. Applying hover to a link element
Say that you have the following element in your web page, just a basic link with the id ‘my-link’.
<a id="my-link">Hi, I am a link!</a>
The id tag lets us apply a style specifically to this element – a web page may only have one instance of a given id, which means you can’t give the id of ‘my-link’ to any more elements on your page. Let the link given above be the one we will be styling.
Now, to apply the actual hover effect, you would put the following code in your CSS – which should preferably be an external stylesheet.
/* Style when no hover */
#my-link {
color: #ccc;
text-decoration: none;
}
/* Style when mouse-overed */
#my-link:hover {
color: #000;
text-decoration: underline;
}
This will give you a basic text link that changes color and is underlined upon mouse over. Not good enough for you? Well, read on over to the next section…
2. Applying hover to a div element
What’s great about cascading style is it’s versatility – it can be applied to any kind of element to change it’s appearance in various ways. Let the following be the div element that you wish to apply styling to:
<div id="my-div">Hi, I am a div!</div>
I will give you a basic example, keep in mind that which styles you apply is totally up to you.
This should give you a div element that changes in appearance when hovered over. Of course, these are only example styles – you may choose to apply a different, better styling to your elements.
Note that while we only experimented with <a> and <div> tags here, the hover selector can be used for styling any HTML tags.
Well, that was all. Not too tough, was it? Hope you enjoy your new-found skills!
A note about pre-loading images
Maybe you’re one of those people who don’t like to see the short lived flicker that occurs when you hover your image links – the time the browser takes to load the rollover image. There are ways around that too, my favorite being the background positioning technique. You can read more about that here.