Skip to content

Pseudo-elements

Just like we have pseudo-classes, which allow us to select things without them being HTML itself, we also have pseudo-elements.

While pseudo-classes allow us to select things based on their state, pseudo-elements create entire elements!

While pseudo-classes use a single colon, pseudo-elements use a double colon (::).

There are a lot of pseudo-elements, but the two that you will use the most are:

  • ::before
  • ::after

Almost any element can have a pseudo-element on it (we can’t use them on images and other replaced elements, at least for now).

h1::before {
...
}
.title::after {
...
}

There is one property that you must use with ::before and ::after, which is the content property. Without content, these pseudo-elements don’t exist.

It also needs to either have a display or position.

.title::after {
content: '';
/* either */
display: /* something */
/* or */
position: /* something */
}

See the Pen before and after demo by Kevin (@kevinpowell) on CodePen.

They go before, and after, the content inside the element

Section titled “They go before, and after, the content inside the element”

One common misconception with pseudo-elements is that they go before or after the element we’ve selected, but they go before, or after, the content inside of that element.

You can use strings of text as the content, use url() to bring images, use one of the gradient value functions, or just keep it blank to create your own decorations.

Some quick wins that many people don’t know about are features like open and close quotes.

See the Pen quotes by Kevin (@kevinpowell) on CodePen.

For a long time, the ::before and ::after pseudo-elements were problematic from an accessibility point of view.

Different assistive technologies would treat them in different ways, and a lot of official guidelines say that using them to insert anything other than decorative content fails certain accessibility guidelines.

Screen readers will read text that’s inserted using ::before and ::after, and these days, we can also supply alternative text, and browser support is reaching decent levels for it.

.toast-notification.error {
content: url('images/exclamation.svg') / 'Error!';
}

There are other pseudo-elements

There are a lot of other types of pseudo-elements! I only talked about ::before and ::after because they’re the ones you’d use the most often.

Most of the others are for fairly specific use cases, though two that you might want to look into more now are ::marker and ::selection.