Skip to content

Pseudo-elements

Learn how to use the ::before and ::after pseudo-elements

  • Lesson
  • 2 min read
  • 3 of 4 in this chapter

Pseudo-elements are different from pseudo-classes in that they are used to style a part of an element, while pseudo-classes are used to style a whole element. The syntax for pseudo-elements is similar, but they are preceded by two colons instead of one. Two of the more common pseudo-classes are ::before and ::after. Here's the basic setup for a pseudo-element before a paragraph (make sure you have a paragraph in HTML first, of course):

CSS
p::before {
 content: '';
}

The content property is necessary even if there's no text content, because otherwise it's set to the default, which is "content: none".

The pseudo-element can be styled completely separately from the paragraph.

CSS
p::before {
 content: '';
 background-color: blue;
 display: block;
 height: 100px;
 width: 100px;
}

You can also add text or images to the content. To add an image, write its URL like this:

CSS
p::before {
 content: url(cheetah.png);
}

The ::after pseudo-element works just like this, except it's added after the content of the main element.

Some other pseudo-elements include:

  • ::first-letter changes the style of only the first letter in an element (this is sometimes used for news articles and such)
  • ::first-line styles the first line of text in an element
  • ::selection adds special styling to the part of an element that is selected by the user (can be used to change the default highlighting color)