CodeBlanks Logo Icon CodeBlanks

::before and ::after

CSS course · Intermediate · Lesson 19/98

Learn ::before and ::after pseudo-elements.

What are ::before and ::after?

In CSS, a pseudo-element styles a specific part of an element without adding new HTML tags. The two best known are ::before and ::after. They drop a new box inside the targeted element, before and after its content.

The double colon (::) marks a pseudo-element. A single colon still works, but the double colon is the modern form. These boxes never appear in the HTML source; CSS alone makes them visible.

Pseudo-element syntax

The pseudo-element syntax: a double colon and a name after the selector. a::after adds a box at the end of every link; .card::before adds one at the start of every element with class="card".

These boxes behave like real elements: you can give them color, margin, even a background. They never show up in the HTML source; the browser draws them live.

Exercise Add a badge with ::before

Add a ::before pseudo-element to the .badge class selector. Inside, declare a content value (a quoted string), then color: white and background: red.

Show example solution
/* add ::before for the badge */
.badge::before {
  content: "New";
  color: white;
  background: red;
}

Test yourself

  1. Where does the ::after pseudo-element land?

    a::after {
      content: '↗';
    }
    • Right before the tag, outside it
    • Inside the element, after its content
    • Only inside the body element
    • Next to the selector, as an independent element
    Show answer

    Inside the element, after its content — Correct. ::after adds a box inside the element, after the existing content.

  2. Write the ::after pseudo-element

    ____ {
      content: '↗';
    }
    Show answer
    ::after {
      content: '↗';
    }
  3. Match each pseudo-element to its target

    ::before
    Box before the content
    ::after
    Box after the content
    ::first-letter
    The first letter
    ::selection
    Selected text

All lessons in Intermediate