::before and ::afterCSS pseudo-elements are keywords prefixed with double colons (::) that allow developers to style specific parts of an element—such as the first letter, first line, or insert artificial content before/after an element box.
Common CSS pseudo-elements:
/* Insert decorative content before/after element */
.card::before {
content: "★ ";
color: #f59e0b;
}
.link-external::after {
content: " ↗";
font-size: 0.8em;
}
/* Typography pseudo-elements */
p::first-letter {
font-size: 2rem;
color: #38bdf8;
}
::selection {
background-color: #38bdf8;
color: #0f172a;
}
Key pseudo-elements:
::before & ::after: Inserts visual decor or iconography before or after element content (requires content: "").::first-letter: Targets and styles the very first letter of a paragraph (drop caps).::first-line: Formats the first line of text dynamically.::selection: Customizes background and text colors when users highlight text with a mouse cursor.flowchart LR
A["::before Content"] --> B["Element Inner Content Area"]
B --> C["::after Content"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Pseudo-Elements Example</title>
<style>
.custom-quote {
position: relative;
background-color: #1e293b;
padding: 1.5rem 1.5rem 1.5rem 3rem;
border-radius: 8px;
max-width: 500px;
}
/* Insert decorative quotation mark pseudo-element */
.custom-quote::before {
content: "“";
position: absolute;
top: 10px;
left: 15px;
font-size: 3rem;
color: #38bdf8;
line-height: 1;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Custom Decorative Blockquote</h2>
<div class="custom-quote">
<p style="margin: 0;">Pseudo-elements allow adding decorative styling accents without adding extra HTML tags!</p>
</div>
</body>
</html>
content: "" on ::before and ::after: Pseudo-elements will not render on screen without a content property declaration.:: for pseudo-elements: Differentiates pseudo-elements (::before) from pseudo-classes (:hover).::before for icons and badge indicators: Keeps decorative presentation inside CSS rather than cluttering HTML templates.Create a CSS rule for .required-field::after that inserts a red asterisk (content: " *"; color: #ef4444;)!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.