How do I use the hover, active, and focus pseudo-classes to format links?
Author: Deron Eriksson
Description: This CSS tutorial describes how to use the :hover, :active, and :focus pseudo-classes to format elements in response to user interaction with a web page.
Tutorial created using: Windows XP

The :hover, :active, and :focus pseudo-classes can be used to control the formatting of links in response to user actions in a browser. The :hover and :active pseudo-classes appear to be well-supported in both IE7 and Firefox, but :focus appears to work only in Firefox. The :hover pseudo-class determines formatting when a user mouses-over a link. The :active pseudo-class is applied when a link is clicked on via a mouse button to when the button is released. The :focus pseudo-class is applied when a link has focus, which is obtained by things such as tabbing to the link via the keyboard.

When applying multiple pseudo-classes such as :link, :visited, :hover, :active, and :focus, the order of your rules is important due to cascading. So, if things aren't behaving the way you expect, you might want to switch the order of your rules to see if this fixes things.

The style-test.html file demonstrates our pseudo-classes. If a link has focus by tabbing to it on the keyboard, it will be colored yellow (in Firefox). If we hover over a link with the mouse, the link will be blue and bold. If we click on a link and hold the mouse button down, the link will be red and italicized.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
a { color: green; }
a:focus {color: yellow; }
a:hover { color: blue; font-weight: bold; }
a:active { color: red; font-style: italic; }
<a href="">Go to Google</a>
<a href="http://localhost:8080">Go to localhost</a>

Here we can see style-test.html in IE7. The link color is green.

Default links are green

If we hover the mouse pointer over the link, it turns blue and bold.

Hovering over the link turns it blue and bold

If we click the link and hold down the mouse button, we can see that the link turns italicized and red.

Clicking and holding down the mouse button on the link turns it red and italicized

Let's also examine the :focus pseudo-class in different browsers. If we tab to a link in IE7, it appears red and italicized, but it does not appear yellow. If we tab to a link in Firefox, we can see that it appears yellow. Since the results are different, I would tend to avoid using the :focus pseudo-class and stick with the :hover and :active pseudo-classes for cross-browser compatibility.

The :focus pseudo-class is supported by Firefox but not IE7