::first-line
Baseline 广泛可用 *
试一试
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 不起作用。
对于 CSS background 来说,::first-line 伪元素就像一个行内元素,这意味着在左对齐的第一行中,背景可能无法一直延伸到右边距。
允许的属性
只有 CSS 属性的一个小部分可以与 ::first-line 伪元素一起使用。
- 所有字体相关属性:
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。
语法
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 |
浏览器兼容性
加载中…