CSS Pseudo-elements

What Are Pseudo-elements?

CSS pseudo-elements let you style specific parts of an element without adding extra HTML tags. They are especially useful for decoration, inserting extra content, or applying fine-grained text styling.

Pseudo-elements are written with a double colon (::) to distinguish them from pseudo-classes, though some older browsers still support the single colon syntax.

Common Pseudo-elements

  • ::before — add content before the element
  • ::after — add content after the element
  • ::first-line — style the first line of a block of text
  • ::first-letter — style the first letter of text
  • ::selection — style text when it is selected

Visual Examples

This paragraph uses ::before.

.before-example::before {
  content: "⭐ ";
}

This paragraph uses ::after

.after-example::after {
  content: " •";
}

this paragraph uses ::first-letter to style the first letter.

.first-letter-example::first-letter {
  font-size: 2rem;
  color: red;
  font-weight: bold;
}

This paragraph uses ::first-line to make the first line bold and aqua.

.first-line-example::first-line {
  color: #00ffcc;
  font-weight: bold;
}

Try selecting this text to see ::selection in action!

.selection-example::selection {
  background-color: yellow;
  color: black;
}

Best Practices

  • Use for decorative or formatting enhancements
  • Always use :: syntax for modern CSS
  • Avoid relying on ::before/::after for essential content

Practice Prompt

Use ::first-letter to make the first letter of a paragraph large and red.

<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
  font-size: 2rem;
  color: red;
  font-weight: bold;
}
</style>
</head>
<body>

<p>
  this is a paragraph where the first letter will be large, bold, and red.
</p>

</body>
</html>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic