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.

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

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.