The ::first-letter CSS pseudo-element allows you to target and style the first letter of a block-level element. This is particularly useful for creating drop caps, enhancing the visual appeal of your text content, such as in articles, blog posts, or any long-form text.
Syntax
selector::first-letter {
/* CSS properties to apply to the first letter */
}
Example
<p>This is a paragraph with a styled first letter.</p>
p::first-letter {
font-size: 2em;
color: red;
text-transform: uppercase;
font-weight: bold;
}
Explanation:
- Selector: Specifies the element(s) whose first letter you want to style. In this case, it’s the
<p>element. ::first-letterpseudo-element: Targets the first letter of the first word within the selected element.- CSS properties: Define the styles you want to apply to the first letter:
font-size: Enlarges the letter.color: Changes the letter’s color.text-transform: Converts the letter to uppercase.font-weight: Makes the letter bold.
Additional Considerations
- Nested Elements: If the first word contains nested elements (e.g.,
<span>), the::first-letterwill target the first letter of the first word within the parent element. - Whitespace: Leading and trailing whitespace within the first word might affect the styling. Ensure consistent spacing for predictable results.
- Combining with Other Pseudo-Elements: You can combine
::first-letterwith other pseudo-elements like::first-lineto style the first line of the first word.
Example with ::first-line:
p::first-line {
font-style: italic;
background-color: lightblue;
}
p::first-letter {
/* ... other styles ... */
}
Advanced Example: Animated First Letter
You can also add animations to the first letter for dynamic effects:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animated First Letter</title>
<style>
p::first-letter {
display: inline-block;
animation: bounce 2s infinite;
font-size: 2em;
color: #1e90ff; /* DodgerBlue */
}
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
}
</style>
</head>
<body>
<p>
Dynamic styling can make your content more engaging and visually appealing to your audience.
</p>
</body>
</html>
The first letter “D” of the paragraph will bounce up and down continuously, attracting attention and adding a lively touch to the text.