Pseudo-Classes and Pseudo-Elements

Things get really interesting with pseudo-class selectors and pseudo-element selectors. These selectors let you assign styles to structures that don’t necessarily exist in the document, or to phantom classes that are inferred by the state of certain elements, or even by the state of the document itself. In other words, the styles are applied to pieces of a document based on something other than the structure of the document, and in a way that cannot be precisely deduced simply by studying the document’s markup.

It may sound like I’m applying styles at random, but I’m not. Instead, I’m applying styles based on somewhat ephemeral conditions that can’t be predicted in advance. However, the circumstances under which the styles will appear are, in fact, well-defined. Think of it this way: during a sporting event, whenever the home team scores, the crowd will cheer. You don’t know exactly when during a game the scoring will happen, but when it does, the crowd will cheer, just as predicted. The fact that you can’t predict the moment of the cause doesn’t make the effect any less expected.

Pseudo-Class Selectors

Let’s begin by examining pseudo-class selectors since they’re better supported by browsers and are therefore more widely used.

Consider the anchor element (a), which, in HTML and XHTML, establishes a link from one document to another. Anchors are always anchors, of course, but some anchors refer to pages that have already been visited, while others ...

Get Cascading Style Sheets: The Definitive Guide, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.