我有以下代码:
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>
问题是伪元素适用于 p
标签并将第一行更改为指定的颜色,但同样不适用于 span
标签。
最佳答案
根据 MDN :
A first line has only meaning in a block-container box, therefore the ::first-line pseudo-element has only an effect on elements with a display value of block, inline-block, table-cell or table-caption. In all other cases, ::first-line has no effect.
以下是 W3C Spec 的摘录: (Section 7.1.1 First formatted line definition in CSS)
In CSS, the ::first-line pseudo-element can only have an effect when attached to a block-like container such as a block box, inline-block, table-caption, or table-cell.
自 span
elements are display: inline
by default ::first-line
选择器对其没有影响。如果我们将 span
的 display
更改为 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;
}
<h3>Default Span</h3>
<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>
<h3>Span with display as block</h3>
<span class='block'> 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>
<h3>Span with display as inline-block</h3>
<span class='inline-block'> 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>
关于html - 为什么::first-line 不适用于 p/div 标签之类的跨度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35577974/