Skip to main content

Inserting content with ::before and ::after

· 4 min read
Luke Owen
Lead Front End Developer @ Lunio

Pseudo elements

CSS has five pseudo elements:

  • ::first-line
  • ::first-letter
  • ::selection
  • ::before
  • ::after

In this post I’m going to be focusing on the last two, ::before and ::after

These are the most commonly used, they allow you to put content into the page without touching any HTML.

Quick note on syntax

As of CSS3 all pseudo-elements use double-colons :: to differentiate them from pseudo-elements, before this they used a single-colon.

While most browsers will recognise both, unless you’re supporting Internet Explorer 8 (and in 2019 you shouldn’t be), you should be using double-colons.

How it works

::before and ::after allow you to add extra content to your HTML, directly from your stylesheet.

The content property is used to define the new content. It must be something simple like text or an image, so you can’t use a pseudo-element to inject HTML.

.class-name::before {
content: "lorem";
}

Both selectors place the new content inside the element, ::before puts it before the element content, while ::after puts it after (they’re both very well named).

<div>
::before

<!-- div content goes here -->

::after
</div>

Some important things to remember

  • The new content is inline by default.
  • The content property is required (but can be an empty string).
  • Once in the DOM you can style the new content just like any other element.

Essentially these pseudo-elements give you two new elements to play with for every one that’s in your HTML. This allows you to do some pretty cool things…

Why use them

There are a tonne of reasons you’d want to add new content via CSS, I’m just going to cover off some of the main ones

To add icons

A lot of icon libraries (like FontAwesome) use pseudo-elements to display their icons. In the example below I’m adding an icon to any link that opens in a new tab.

Adding fancy styling to elements

In this example I’m using two pseudo-elements:

  • A FontAwesome icon before the blockquote
  • A hyphen before the cite

Creating nice borders

Borders take up the full width of their element (as part of the Box Model). But by adding a pseudo-element, we can style them however we like.

Another benefit is the extra styling options we get. Since it’s just a regular element we can use gradients, transparency, and border-radius.

Pseudo-elements are a quick way to add spacers between breadcrumb items, without changing the markup.

Making shapes

The pencil below consists of one div and some CSS. Nope, I’ve never found a use case for it either..

I can also do Yin Yang with one element.

Replacing HTML content

Let's be clear…

Under normal circumstances don’t do this

But – there may be occasions when you need to change text without touching the markup.