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

瀏覽器相容性

另見