0
0
CssHow-ToBeginner · 3 min read

How to Use ::first-letter in CSS for Styling First Letters

Use the ::first-letter pseudo-element in CSS to target and style the first letter of a block of text. It allows you to change properties like font size, color, and weight specifically for that first letter.
📐

Syntax

The ::first-letter pseudo-element targets the first letter of the first line of a block-level element. It is written after the selector like this:

  • selector::first-letter { property: value; }

This applies styles only to the first letter inside the selected element.

css
p::first-letter {
  color: red;
  font-size: 2rem;
  font-weight: bold;
}
💻

Example

This example shows how to style the first letter of a paragraph to be bigger, bold, and red. The rest of the paragraph stays normal.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Letter Example</title>
<style>
p::first-letter {
  color: red;
  font-size: 2rem;
  font-weight: bold;
}
</style>
</head>
<body>
<p>This is a paragraph where the first letter is styled differently using <code>::first-letter</code>.</p>
</body>
</html>
Output
A paragraph of text where the first letter 'T' is large, bold, and red, and the rest of the text is normal black and normal size.
⚠️

Common Pitfalls

Some common mistakes when using ::first-letter include:

  • Trying to use it on inline elements like span which may not work as expected because it targets block-level elements.
  • Applying styles that are not allowed on ::first-letter, such as float or vertical-align.
  • Expecting it to style the first letter of every line instead of just the first letter of the first line.

Always test your styles in different browsers to ensure consistent behavior.

css
/* Wrong: Applying ::first-letter to inline element */
span::first-letter {
  color: blue;
}

/* Right: Apply to block element like paragraph */
p::first-letter {
  color: blue;
}
📊

Quick Reference

Tips for using ::first-letter:

  • Works only on block-level elements like p, div, article.
  • Can style font, color, size, weight, and some text decorations.
  • Cannot apply layout properties like float or position.
  • Use for decorative effects like drop caps or emphasis on first letter.

Key Takeaways

Use ::first-letter to style only the first letter of block-level text elements.
It supports font and color styles but not layout properties like float or position.
Apply it to elements like p or div, not inline elements like span.
Great for creating drop caps or emphasizing the first letter visually.
Test in multiple browsers for consistent appearance.