0
0
CssHow-ToBeginner · 3 min read

How to Use ::first-line in CSS for Styling First Line of Text

Use the ::first-line pseudo-element in CSS to target and style only the first line of a block of text. It allows you to change font, color, or other text styles for that first line without affecting the rest.
📐

Syntax

The ::first-line pseudo-element targets the first line of text inside a block-level element. It is written after the selector and two colons.

  • selector::first-line - selects the first line of the element matched by selector.
  • Only certain CSS properties can be used with ::first-line, mostly related to text formatting.
css
p::first-line {
  color: blue;
  font-weight: bold;
}
💻

Example

This example shows how to make the first line of a paragraph bold and blue, while 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-line Example</title>
<style>
p::first-line {
  color: blue;
  font-weight: bold;
}
</style>
</head>
<body>
<p>This is a paragraph where only the first line will appear in blue and bold. The rest of the text remains normal and unchanged.</p>
</body>
</html>
Output
A paragraph of text where only the first line is bold and blue, and the rest is normal black text.
⚠️

Common Pitfalls

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

  • Trying to apply unsupported CSS properties like background-color or margin which do not work on ::first-line.
  • Using ::first-line on inline elements like span, which won't work because it only applies to block-level elements.
  • Expecting exact control over the first line length, but it depends on the container width and font size.
css
/* Wrong: background-color won't apply */
p::first-line {
  background-color: yellow; /* ignored */
}

/* Correct: color and font-weight work */
p::first-line {
  color: red;
  font-weight: bold;
}
📊

Quick Reference

  • Applies to: Block-level elements like p, div, article.
  • Supported properties: font properties, color, letter-spacing, word-spacing, text-decoration, vertical-align, text-transform, line-height.
  • Unsupported properties: box model properties like margin, padding, border, background.
  • Browser support: Supported in all modern browsers.

Key Takeaways

Use ::first-line to style only the first line of block text.
Only text-related CSS properties work with ::first-line.
It works on block elements, not inline elements.
The first line length depends on container width and font size.
Supported by all modern browsers for consistent styling.