Welcome to Code Couch

Use CSS pseudo classes to enhance accessibility

Posted by at 2:42pm on January 20, 2009.

CSS pseudo-classes are probably not something most people are familiar with – although many developers would make use of them without necessarily being aware of it! When you hover the mouse over a link, many sites will underline the link for you. This is using the hover pseudo-class.

a { text-decoration:none; }
a:hover { text-decoration:underline; }

The above example sets all anchors to have no underline text decoration, and the hover pseudo-class sets all anchors to have an underline on them. When the user hovers their mouse over a link, an underline will show under the link. When they move their mouse away, the hover pseudo-class stops taking effect and the underline is removed.

Pseudo-classes are supported with all modern browsers, but this support is only for the anchor element. Any attempt to use a pseudo-class on any other element will not work in Internet Explorer 6.

There are other pseudo-classes that can be used to provide a more usable experience for those that primarily use a keyboard to navigation through a page. The first of these is the focus pseudo-class (which take affect when the element gains focus – such as tabbing to the element). This pseudo-class can be used to style elements when they receive focus.

Building on the initial example, the addition of a focus pseudo-class will ensure that the same hover effects (in this case some underline text decoration) are applied when the user tabs focus to the anchor.

a { text-decoration:none; }
a:hover, a:focus { text-decoration:underline; }

This would be fine, except that Internet Explorer 6 doesn’t understand the focus pseudo-class at all! The solution is to use the active pseudo-class to extend the CSS rule.

a { text-decoration:none; }
a:hover, a:focus, a:active { text-decoration:underline; }

The order of the pseudo-class rules is important (and if you get the order wrong, you may experience some of the CSS rules displaying inconsistently across browsers). As a general rule, always put pseudo-classes in the following order:

link, visited, hover, focus, active

So, whenever you define a hover pseudo-class CSS rule, consider adding in a focus and then an active pseudo-class at the same time – it will help users that choose to use the keyboard to navigate your site.

Post to Twitter

Tags: ,

Comments

There are no responses to this post.

Leave a reply

Comments are closed for this post.