DevAcademy
LearnCSSPseudo-elements
IntermediateCSS

Pseudo-elements

Learn how to style a specific part of an element, or insert generated content, using ::before, ::after, and other pseudo-elements.

Reading Time

14 min

Lesson

Lesson 19 of 30

Pseudo-elements vs Pseudo-classes

While a pseudo-class targets an existing element in a certain state, a pseudo-element targets a specific part of an element, or inserts content that doesn’t exist in the HTML at all. Pseudo-elements use a double colon, e.g. ::before.

::before and ::after

<style>
  .quote::before {
    content: "\201C"; /* opening curly quote */
    font-size: 24px;
    color: steelblue;
  }
  .quote::after {
    content: "\201D"; /* closing curly quote */
    font-size: 24px;
    color: steelblue;
  }
</style>

<p class="quote">This text is wrapped in generated quote marks.</p>
Output

The content Property

::before and ::after require a content property to appear at all — even content: "" (an empty string) is valid and commonly used just to insert a styled shape, like a decorative line or icon.

Decorative Underline with ::after

<style>
  .heading {
    position: relative;
    display: inline-block;
    padding-bottom: 6px;
  }
  .heading::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 3px;
    background: crimson;
  }
</style>

<h2 class="heading">Section Title</h2>
Output

Other Common Pseudo-elements

Pseudo-elementTargets
::beforeInserted content just before an element’s content
::afterInserted content just after an element’s content
::first-letterThe first letter of a block of text
::first-lineThe first line of a block of text
::selectionThe portion of text currently highlighted by the user

::first-letter

<style>
  .drop-cap::first-letter {
    font-size: 2.5em;
    font-weight: bold;
    color: steelblue;
    float: left;
    margin-right: 4px;
  }
</style>

<p class="drop-cap">This paragraph starts with a large drop-cap letter, a classic print-style effect built with pure CSS.</p>
Output

Not Real DOM Elements

::before and ::after content is purely visual — it doesn’t exist in the DOM and can’t be selected as text or read reliably by all assistive technology, so avoid putting essential information inside it.

Best Practice

Use ::before and ::after for purely decorative content — icons, shapes, and visual flourishes — never for content that conveys meaning users need to read.

Interview Questions

Quick Quiz

1. How many colons do pseudo-elements use, unlike pseudo-classes?

2. Which property is required for ::before or ::after to render anything?

3. Why should ::before/::after avoid holding essential information?