Chapter 3. Pseudo-Class and -Element Selectors
In the previous chapter, you saw how selectors can match a single element or a collection of elements, using fairly simple expressions that match HTML attributes in the document. Those are great if your need is just to style based on attributes, but what if you need to style part of a document based on its current state or structure? Or if you want to select all the form elements that are disabled, or those that are required for form submission to be allowed? For those things, and a great deal more, CSS has the pseudo-class and pseudo-element selectors.
Pseudo-Class Selectors
Pseudo-class selectors let you assign styles to what are, in effect, phantom classes inferred by the state of certain elements, or markup patterns within the document, or even by the state of the document itself.
The term phantom classes might seem a little odd, but it really is the best way to think of how pseudo-classes work. For example, suppose you want to highlight every other row of a data table. You could do that by marking up every other row with something like class="even" and then writing CSS to highlight rows with that class—or (as you’ll soon see) you could use a pseudo-class selector to achieve the same effect, one that will act as if you’ve added all those classes to the markup even though you haven’t.
One aspect of pseudo-classes needs to be made explicit here: pseudo-classes always refer to the element to which they’re attached, and to no other. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access