8.0 Pseudo Classes
A great feature of CSS is that pseudo-classes can be used to add some special effects to some HTML elements. Pseudo-classes are similar to regular classes but are not specified explicitly in the HTML markup. Some pseudo-classes are dynamic in that they are applied as a result of user interaction with the document. CSS1 introduced the :link, :visited, and :active pseudo-classes, but only for the anchor element. These represented the state of links (unvisited, visited, or currently being selected). CSS2 brought along more pseudo-classes and allowed them to be applied to any element, and CSS3 promises even more. The basic syntax for this is:
selector:pseudo-class {property:value;}
A pseudo-class starts with a colon (:). No whitespace is allowed before or after the colon.
| Pseudo Class | Description | CSS |
|---|---|---|
| :active | Adds a style to an element that is activated | 1 | :first-child | Adds a style to an element that is the first child of another element | 2 |
| :focus | Adds a style to an element that has keyboard input focus | 2 |
| :hover | Adds a style to an element when you mouse over it | 1 |
| :lang | Adds a style to an element with a specific lang attribute | 2 |
| :link | Adds a style to an unvisited link | 1 |
| :visited | Adds a style to a visited link | 1 |
You may recall that we used the active, hover, link and visited pseudo classes with the anchor tag earlier in this CSS Tutorial in the section on links. Until cross-browser support improves these are probably still better used only with the anchor tag. For example:
a:hover {color: #ffeedd;}
In this example the above styling will be applied to a link using the anchor tag only when a user hovers over the link. But as we mentioned earlier, other elements can now use these pseudo classes, including those elements that don't normally accept input. For example:
p:hover {background: yellow;}
This would render any paragraph text with a yellow background like below:
This is a line of text that will alter when you hover over it!
As you can probably images, this offers endless possibilities regarding styling effects in a web page.