SJHwebdesigns

Pseudo-class selectors

« Previous: Backgrounds | Next: divs and spans »

Pseudo-class selectors allow you to style elements based on the user’s interaction with that element. These are most commonly used to style links.

a:link, a:visited, a:hover, a:active

  • a:link specifies an <a> tag which is a link (ie, it contains an href attribute).
  • a:visited specifies a link which has already been visited.
  • a:hover specifies a link when the mouse is moved over it
  • a:active specifies a link when it is clicked on

Setting different styles for these different selectors can aid usability, as it helps the user to see which text is a link, and which links they have already visited.

Note: this is the one exception to the rule that CSS selectors can be written in any order: if you use pseudo-class selectors, they will only work if they are defined in the order :link, :visited, :hover, :active. You don’t have to specify all four, but any that you do specify should always be in that order, eg :link, :hover.

Code Output
a:link, a:visited {
     color: #090;
     }
a:hover, a:active {
     color: #a00;
     text-decoration: none;
     }
<p><a href="#">A styled link</a></p>

A styled link

:link and :visited can only be applied to <a> tags. :hover and :active can be applied to any tag, however Internet Explorer version 6 and under ignores :hover and :active for any tags other than <a>.

:focus

:focus can be used to apply styles to form elements such as <input> and <textarea> in which the user has placed their cursor. You can see how this works by clicking inside the search input on this page. Well, you can as long as you're not using Internet Explorer - unfortunately IE, even the latest version, ignores :focus completely. It's still worth using it though, as it can make forms more easy to use for the increasing number of people using modern browsers, and may well be eventually supported by Internet Explorer.

Code Output
input {
     color: #090;
     border: 1px solid #090;
     background: #efe;
     }
input:focus {
     color: #a00;
     border: 1px solid #a00;
     background: #fff;
     }
<form action="">
     <input type="text" value="click in here to focus"/>
</form>

There are many other versatile selectors which can target an element based on the value of its attributes, or what other elements are next to it, however these are not supported in IE 6 and below, so we may have to wait some time before they can be used =(

« Previous: Backgrounds | Next: divs and spans »

Page style: Dark Light