CSS Pseudo-elements

A pseudo-element styles a specific part of an element, such as its first line or first letter, or adds generated content before or after it.

Where a pseudo-class targets a state, a pseudo-element targets a sub-part of an element that does not exist as a separate tag in the HTML. Modern CSS uses a double colon to mark them, which helps tell them apart from pseudo-classes.

The main pseudo-elements

Pseudo-elementTargets
::first-lineThe first line of a block of text
::first-letterThe first letter of a block of text
::beforeGenerated content at the start of an element
::afterGenerated content at the end of an element
::selectionThe part of text the user has highlighted
::placeholderPlaceholder text in an input

A drop cap with first-letter

Enlarge the opening letter

<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
  font-size: 250%;
  font-weight: bold;
  float: left;
  margin-right: 6px;
}
</style>
</head>
<body>

<p>Sunlight poured through the window as the city slowly woke up.</p>

</body>
</html>

This produces the drop cap seen at the start of magazine articles, all from the text already in the paragraph with no extra markup.

Styling the text selection

Custom highlight color

<!DOCTYPE html>
<html>
<head>
<style>
::selection {
  background: #00643c;
  color: #fff;
}
</style>
</head>
<body>

<p>Try selecting this text with your mouse to see the highlight color.</p>

</body>
</html>
Note: Pseudo-elements use a double colon (::) in modern CSS, while pseudo-classes use a single colon (:). Browsers still accept a single colon on the old pseudo-elements for backwards compatibility.

The most powerful pseudo-elements are ::before and ::after, which insert generated content. They are covered in detail in Content Pseudo-elements.

Exercise: CSS Pseudo-elements

Which colon syntax does modern CSS use to distinguish pseudo-elements from pseudo-classes?