我有以下代码:
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
span::first-line {
color: #ff0000;
font-variant: small-caps;
}

<span> This is to check span.This is to check spanThis is to check spanThis is to check spanThis is to check spanThis is to check spanThis is to check spanThis is to check spanThis is to check spanThis is to check span</span>
<p>This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.This is to check p.</p>
&#13;
问题是伪元素适用于p
代码并将第一行更改为指定颜色,但同样不适用于span
代码。
答案 0 :(得分:6)
根据MDN:
第一行仅在块容器框中有意义,因此:: first-line伪元素仅对显示值为block,inline-block,table-cell或table-caption的元素产生影响。在所有其他情况下,:: first-line无效。
以下是W3C Spec的摘录:( 第7.1.1节CSS中第一个格式化的行定义)
在CSS中,:: first-line伪元素只有在附加到类似块的容器(例如块框,内联块,表格标题或表格单元格)时才会有效。
由于span
elements are display: inline
by default ::first-line
选择器对它没有影响。如果我们将display
的{{1}}更改为span
或inline-block
,则会有效。
block
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
span::first-line {
color: #ff0000;
font-variant: small-caps;
}
span.block {
display: block;
}
span.inline-block {
display: inline-block;
}
答案 1 :(得分:3)
The documentation声明 :: first-line 选择器仅适用于块元素。 span 默认为内嵌元素,因此要将其显示为内联块或块< /强>