Pseudo-Classes and Pseudo-Elements

Even more interesting, at least in terms of syntax, are the pseudo-class and pseudo-element selectors. These allow the author to assign styles to structures that don’t necessarily exist in the document, or to things that are inferred by the state of certain elements, or even 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.

This may sound like we’re applying styles at random. Not at all! Instead, the styles are applied based on somewhat ephemeral conditions that can’t be predicted in advance. Nonetheless, the circumstances under which the styles will appear are well-defined. This is sort of like saying, “During a sporting event, whenever the home team scores, the crowd will cheer.” You don’t know exactly when during a game this will happen, but when the right conditions occur, the crowd will do just as predicted. The fact that you can’t predict the exact second (or inning, or quarter) in which this will happen doesn’t make the behavior any less expected whenever the home team does score.

Pseudo-Class Selectors

First we’ll look at pseudo-class selectors, since they’re better supported by browsers and therefore more widely used. Let’s use an example to see how they work; this will take a minute before I reach the actual point, so bear with me.

Consider the ...

Get Cascading Style Sheets: The Definitive Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.