CSS Pseudo-elements
CSS Pseudo-elements
A pseudo-element is used to style a specific part of an element. Unlike pseudo-classes (which describe a state), pseudo-elements target parts like the first letter, first line, or content you insert with CSS.
Pseudo-elements use double colons (::), for example: ::before or ::first-letter.
Pseudo-elements
Common pseudo-elements include:
::first-letter– styles the first letter of a block of text::first-line– styles the first line of a block of text::selection– styles the text the user selects::before– inserts content before an element::after– inserts content after an element
Text Pseudo-elements
You can style the first letter or first line of text to create magazine-like effects.
.article::first-letter {
font-size: 36px;
font-weight: bold;
margin-right: 6px;
}
.article::first-line {
letter-spacing: 0.3px;
}
You can also style selected text:
::selection {
background: #d6e4ff;
}
Content with ::before and ::after
The ::before and ::after pseudo-elements can insert content without changing the HTML. They are often used for icons, badges, separators, and decorative shapes.
To insert content, you must use the content property.
.badge::before {
content: "★ ";
}
.badge::after {
content: " NEW";
}
You can also use them for simple decorative lines:
.title::after {
content: "";
display: block;
width: 60px;
height: 3px;
background: #1f4bd8;
margin-top: 8px;
}
Important Notes
::beforeand::afterare not real DOM elements- They require
contentto show up - They are great for decoration, but avoid inserting important text content
Code Challenge
Goal: Use pseudo-elements to enhance the card UI.
HTML:
<div class="card"> <h3 class="title">Pseudo-elements</h3> <p class="text">Use ::first-letter and ::after to style content.</p> </div>
Task:
- Style the first letter of
.text - Add a decorative underline under
.titleusing::after - Keep the decoration purely visual (empty content)
Try a Solution:
.card {
padding: 16px;
border: 1px solid #ddd;
border-radius: 12px;
max-width: 560px;
}
.title::after {
content: "";
display: block;
width: 70px;
height: 3px;
background: #1f4bd8;
margin-top: 8px;
}
.text::first-letter {
font-size: 32px;
font-weight: bold;
margin-right: 6px;
}
What’s Next?
Next, you will learn how to control transparency using CSS opacity.