このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

::first-line

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.

* Some parts of this feature may have varying levels of support.

::first-lineCSS擬似要素で、ブロックコンテナーの先頭行にスタイルを適用します。

試してみましょう

p::first-line {
  font-size: 1.2rem;
  font-weight: bold;
  text-decoration: underline;
}
<p>
  In warm ocean waters around the world, you may see a strange sight: A fish
  leaping from the water and soaring dozens of meters before returning to the
  ocean's depths. Early Mediterranean sailors thought these flying fish returned
  to the shore at night to sleep, and therefore called this family of marine
  fish Exocoetidae.
</p>

::first-line の効果は、要素内のテキストの先頭行の長さとコンテンツによって制限されます。先頭行の長さは、要素の幅、文書の幅、テキストのフォントサイズなど、多くの要因に依存します。要素の最初の子(先頭行の最初の部分となる)がインラインテーブルなどのインラインブロックレベル要素である場合、::first-line は効果を持ちません。

メモ: Selectors Level 3 では二重コロン (::) を導入し、擬似要素を単一コロン (:) の擬似クラスと見分けやすくしています。ブラウザーは ::first-line と、CSS2 で導入された :first-line の両方を受け付けます。

CSS の background の目的上、::first-line 擬似要素はインラインレベル要素と同様に扱われます。つまり、左揃えの先頭行では、背景が右マージンまで完全に広がらない場合があります。

利用可能なプロパティ

::first-line 擬似要素では、一部の CSS プロパティのみが利用できます。

構文

css
::first-line {
  /* ... */
}

段落の先頭行のスタイル設定

HTML

html
<p>
  スタイルはこの段落の先頭行にのみ適用されます。
  その後のすべての文字列は普通のスタイルになります。分かりますか?
</p>

<span>
  ブロックレベル要素ではないので、この文字列の先頭行は、特殊なスタイルになりません。
</span>

CSS

css
::first-line {
  color: blue;
  font-weight: bold;

  /* 警告: これらを使用しないでください */
  /* ::first-line 擬似要素では多くのプロパティが無効になります */
  margin-left: 20px;
  text-indent: 20px;
}

結果

SVG の text 要素の先頭行をスタイル設定

この例では、SVG の <text> 要素の先頭行を ::first-line 擬似要素を使用してスタイル設定します。

メモ: 執筆時点で、この機能は対応が限定されています

HTML

html
<svg viewBox="0 0 320 150">
  <text y="20">Here is an English paragraph
that is broken into multiple lines
in the source code so that it can
be more easily read and edited
in a text editor.
  </text>
</svg>

CSS

SVG の <text> 要素を複数行に折り返すには、white-space CSS プロパティを使用します。その後、::first-line 擬似要素で最初の行を選択します。

css
text {
  white-space: break-spaces;
}

text::first-line {
  fill: blue;
  font-weight: bold;
}

結果

仕様書

Specification
CSS Pseudo-Elements Module Level 4
# first-line-pseudo

ブラウザーの互換性

関連情報