::first-line

Baseline 广泛可用 *

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

* 此特性的某些部分可能存在不同级别的支持。

::first-line CSS 伪元素用于对块容器的第一行应用样式。

试一试

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 不起作用。

注意:选择器级别 3 引入了双冒号表示法(::)以将伪元素与单冒号(:伪类区分开来。浏览器接受 ::first-line:first-line,后者在 CSS2 中引入。

对于 CSS background 来说,::first-line 伪元素就像一个行内元素,这意味着在左对齐的第一行中,背景可能无法一直延伸到右边距。

允许的属性

只有 CSS 属性的一个小部分可以与 ::first-line 伪元素一起使用。

语法

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

示例

段落首行样式

HTML

html
<p>
  Styles will only be applied to the first line of this paragraph. After that,
  all text will be styled like normal. See what I mean?
</p>

<span>
  The first line of this text will not receive special styling because it is not
  a block-level element.
</span>

CSS

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

  /* WARNING: DO NOT USE THESE */
  /* Many properties are invalid in ::first-line pseudo-elements */
  margin-left: 20px;
  text-indent: 20px;
}

结果

SVG 文本元素的首行样式

在此示例中,我们使用 ::first-line 伪元素设置 SVG <text> 元素的第一行样式。

注意:撰写本文时,此功能支持有限

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;
}

结果

规范

规范
CSS 伪元素模块 Level 4
# first-line-pseudo

浏览器兼容性

另见