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>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>Other Common Pseudo-elements
| Pseudo-element | Targets |
|---|---|
| ::before | Inserted content just before an element’s content |
| ::after | Inserted content just after an element’s content |
| ::first-letter | The first letter of a block of text |
| ::first-line | The first line of a block of text |
| ::selection | The 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>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.