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
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>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?