CSS Selectors: How to Use CSS Pseudo-Elements

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Pseudo-elements are used to style a specific part of an element, or to insert content before or after an element.

They start with a double colon ::.

You may see them with a single colon in older code. The double colon syntax distinguishes them from pseudo-classes.

Common Pseudo-Elements

Pseudo-elementDescription
::beforeInsert content before the element
::afterInsert content after the element
::first-letterStyle the first letter
::first-lineStyle the first line
::selectionStyle selected text
::placeholderStyle input placeholder text

::first-letter and ::first-line

Great for typographic effects:

p::first-letter {
  font-size: 2em;
  font-weight: bold;
  float: left;
  margin-right: 0.1em;
}

p::first-line {
  font-variant: small-caps;
}

::before and ::after

These pseudo-elements insert generated content. They require the content property:

.quote::before {
  content: '"';
}

.quote::after {
  content: '"';
}

Adding Icons

.external-link::after {
  content: ' ↗';
}

.required-field::after {
  content: '*';
  color: red;
}

Decorative Elements

.fancy-title::before {
  content: '';
  display: block;
  width: 50px;
  height: 3px;
  background: blue;
  margin-bottom: 10px;
}

Clearing Floats

The classic clearfix technique:

.clearfix::after {
  content: '';
  display: table;
  clear: both;
}

::selection

Style text when the user selects it:

::selection {
  background: yellow;
  color: black;
}

p::selection {
  background: blue;
  color: white;
}

::placeholder

Style placeholder text in form inputs:

input::placeholder {
  color: #999;
  font-style: italic;
}

Important Notes

  1. ::before and ::after content is not selectable by users
  2. Screen readers may or may not read generated content
  3. The content property is required for ::before and ::after to work
  4. You cannot use ::before and ::after on replaced elements like img or input

Lessons in this unit:

0: Introduction
1: How to Use Basic CSS Selectors
2: How to Use CSS Attribute Selectors
3: How to Use CSS Pseudo-Classes
4: ▶︎ How to Use CSS Pseudo-Elements