Pseudo-classes and Pseudo-elements

Though you’ve probably used pseudo-classes and pseudo-elements in your code, you may not have thought about what they are or the difference between them.

Pseudo-classes let us style objects based on information distinct from the document tree, or that’s unable to be expressed using simple selectors. For example, an element can only have a hover or focus state once the user interacts with it. With the :hover and :focus pseudo-classes, we can define styles for those states. Otherwise, we’d have to rely on scripting to add and remove class names.

Pseudo-elements, on the other hand, let us style elements that aren’t directly present in the document tree. There’s no firstletter element in HTML, so we need another way to select it. The ::first-letter pseudo-element gives us that capability.


The CSS Pseudo-elements Module Level 4 specification 6clarifies behavior for ex- isting pseudo-elements and defines several new ones. Only a few, however, have any degree of support in current browsers. Those are the ones we’ll focus on here:

::before inserts additional generated content before the content of an element
::after inserts additional generated content after the content of an element
::first–letter selects the first letter of an element
::first–line selects the first line of an element
::selection styles text selected by the cursor

Of these, ::first–letter, ::first–line, and ::selection affect content that’s part of the document source. The ::before and ::after pseudo-elements, on the other hand, inject content into a document without it existing in the document source.