::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

浏览器兼容性

另见