::first-letter

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

::first-letter CSS 偽元素用於對塊容器第一行的首字母應用樣式,但前提是其前面沒有其他內容(例如影像或內聯表格)。

試一試

p::first-letter {
  font-size: 1.5rem;
  font-weight: bold;
  color: brown;
}
<p>
  Scientists exploring the depths of Monterey Bay unexpectedly encountered a
  rare and unique species of dragonfish. This species is the rarest of its
  species.
</p>

<p>
  When Robison and a team of researchers discovered this fish, they were aboard
  a week-long expedition.
</p>

識別元素的首字母並非總是那麼簡單

  • 首字母前面或緊隨其後的標點符號也包含在匹配中。標點符號包括在(Ps)、(Pe)、初始引號(Pi)、最終引號(Pf)和其他標點符號(Po)類別中定義的任何 Unicode 字元。
  • 某些語言中的二合字母總是同時大寫,例如荷蘭語中的 IJ。在這種情況下,二合字母的兩個字母都應由 ::first-letter 偽元素匹配。
  • ::before 偽元素和 content 屬性的組合可能會在元素的開頭插入一些文字。在這種情況下,::first-letter 將匹配此生成內容的第一個字母。

注意: CSS 引入了 ::first-letter 記法(帶兩個冒號)以區分偽類偽元素。為了向後相容,瀏覽器也接受早期引入的 :first-letter

瀏覽器對荷蘭語 IJ 等二合字母的支援不佳。檢視下面的相容性表格以瞭解當前支援情況。

允許的屬性

只有一小部分 CSS 屬性可以與 ::first-letter 偽元素一起使用

語法

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

示例

基本首字下沉

在此示例中,我們將使用 ::first-letter 偽元素對緊隨 <h2> 之後的段落的首字母建立首字下沉效果。

HTML

html
<h2>My heading</h2>
<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
  eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
  voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
  kasd gubergren, no sea takimata sanctus est.
</p>
<p>
  Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie
  consequat.
</p>

CSS

css
p {
  width: 500px;
  line-height: 1.5;
}

h2 + p::first-letter {
  color: white;
  background-color: black;
  border-radius: 2px;
  box-shadow: 3px 3px 0 red;
  font-size: 250%;
  padding: 6px 3px;
  margin-right: 6px;
  float: left;
}

結果

對特殊標點符號和非拉丁字元的影響

此示例說明了 ::first-letter 對特殊標點符號和非拉丁字元的影響。

HTML

html
<p>
  Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie
  consequat.
</p>
<p>-The beginning of a special punctuation mark.</p>
<p>_The beginning of a special punctuation mark.</p>
<p>"The beginning of a special punctuation mark.</p>
<p>'The beginning of a special punctuation mark.</p>
<p>*The beginning of a special punctuation mark.</p>
<p>#The beginning of a special punctuation mark.</p>
<p>「特殊的漢字標點符號開頭。</p>
<p>《特殊的漢字標點符號開頭。</p>
<p>"特殊的漢字標點符號開頭。</p>

CSS

css
p::first-letter {
  color: red;
  font-size: 150%;
}

結果

SVG 文字元素中首字母的樣式

在此示例中,我們使用 ::first-letter 偽元素對 SVG <text> 元素的第一個字母進行樣式設定。

注意:在撰寫本文時,此功能支援有限

HTML

html
<svg viewBox="0 0 300 40">
  <text y="30">First letter in &lt;text&gt; SVG</text>
</svg>

CSS

css
text {
  font-family: sans-serif;
}

text::first-letter {
  font-family: serif;
  font-size: 2rem;
  font-weight: 600;
  fill: tomato;
  stroke: indigo;
}

結果

規範

規範
CSS 偽元素模組 Level 4
# first-letter-pseudo

瀏覽器相容性

另見