Lesson Weekend

Unlike pseudo-classes, which capture state information about an existing DOM element, pseudo-elements allow us to create items that don't normally exist in the DOM tree using CSS alone.

For instance, the ::after pseudo-element is used to insert additional content after the HTML element it’s matched with. Consider the following basic example. Pretend we have <p> tags that look like this:


If we created the following CSS rule to target those <p> tags with a pseudo-element, like this...

p::after {
  content: " is really rad!";

...the <p> tags rendered in the browser would actually read as follows:

CSS is really rad!

Even though the is really rad! part isn't included in the HTML, the ::after pseudo-element inserted this extra content after all p elements.

But since this content was added with CSS, not HTML, it doesn’t exist in the DOM. This is why it's called a pseudo element; because it isn't technically part of the DOM like our hard-coded HTML is; it's added after-the-fact with style rules.

How do these differ from the pseudo-classes we just learned about? Growing with the Web's article Pseudo-classes vs Pseudo-elements offers a helpful tip to discern between the two:

"If you still have difficulty remembering the difference, just think of what the names ‘pseudo-element’ and ‘pseudo-class’ are actually implying. A pseudo-element is a ‘fake’ element, it isn’t really in the document with the ‘real’ ones. Pseudo-classes are like ‘fake’ classes that are applied to elements under certain conditions, much like how you would manipulate the classes of elements using JavaScript."

Supported CSS Pseudo-Elements

There are currently 5 supported pseudo-elements:

  • ::after inserts content after the specified element.

  • ::before inserts content before the specified element.

  • ::first-letter selects the first letter of a specified element.

  • ::first-line selects the first line of a specified element.

  • ::selection selects the portion of an element actively selected by a user.

Pseudo-Element Syntax

You'll notice in the list above that each pseudo-element is preceded by two colons. As Smashing Magazine's Ultimate Guide to CSS Pseudo-Classes and Pseudo-Elements describes:

The double colon (::) was introduced in CSS3 to differentiate pseudo-elements such as ::before and ::after from pseudo-classes such as :hover and :active. All browsers support double colons for pseudo-elements except Internet Explorer (IE) 8 and below.

Required Reading: The Lowdown on :before and :after in CSS

Please read The Lowdown on :before and :after in CSS from Mayven to gain a better understanding and see more examples of pseudo-elements in action.

And, as always, you can check out the MDN Documentation on Pseudo-Elements for more information.