03 Nov 2021

::before and ::after

In CSS, ::before and ::after are pseudo-elements that allow you to insert content before or after an element's actual content. These pseudo-elements are often used to add decorative or supplementary elements to an element without modifying the HTML structure.

One simple example of using ::before pseudo-elements is to provide quotation marks. Here we use both ::before and ::after to insert quotation characters.

<q>Some quotes</q>, he said, <q>are better than none.</q>
q::before {
  content: "«";
  color: blue;
}

q::after {
  content: "»";
  color: red;
}

Single-colon or double-colon?

  • double-colon selectors are pseudo-elements
  • single-colon selectors are pseudo-selectors

::before and ::after are pseudo-elements, so it should use a double-colon.

:: select a part of something for which there is no HTML element for (no span, no div).

: selects something that already exists, like the :nth-child(2)

So you should use ::before, but most modern browsers support it both ways, since a lot of sites use :before.