::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.
試してみましょう
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 プロパティのみが利用できます。
- フォントに関する全プロパティ:
font,font-kerning,font-style,font-variant,font-variant-numeric,font-variant-position,font-variant-east-asian,font-variant-caps,font-variant-alternates,font-variant-ligatures,font-synthesis,font-feature-settings,font-language-override,font-weight,font-size,font-size-adjust,font-stretch,font-family - 背景に関する全プロパティ:
background-color,background-clip,background-image,background-origin,background-position,background-repeat,background-size,background-attachment,background-blend-mode colorプロパティword-spacing,letter-spacing,text-decoration,text-transform,line-heighttext-shadow,text-decoration,text-decoration-color,text-decoration-line,text-decoration-style,vertical-align
構文
::first-line {
/* ... */
}
例
>段落の先頭行のスタイル設定
HTML
<p>
スタイルはこの段落の先頭行にのみ適用されます。
その後のすべての文字列は普通のスタイルになります。分かりますか?
</p>
<span>
ブロックレベル要素ではないので、この文字列の先頭行は、特殊なスタイルになりません。
</span>
CSS
::first-line {
color: blue;
font-weight: bold;
/* 警告: これらを使用しないでください */
/* ::first-line 擬似要素では多くのプロパティが無効になります */
margin-left: 20px;
text-indent: 20px;
}
結果
SVG の text 要素の先頭行をスタイル設定
この例では、SVG の <text> 要素の先頭行を ::first-line 擬似要素を使用してスタイル設定します。
メモ: 執筆時点で、この機能は対応が限定されています。
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 擬似要素で最初の行を選択します。
text {
white-space: break-spaces;
}
text::first-line {
fill: blue;
font-weight: bold;
}
結果
仕様書
| Specification |
|---|
| CSS Pseudo-Elements Module Level 4> # first-line-pseudo> |