::before 和 ::first-line 不能正常工作

::before and ::first-line don't work right correctly

MDN 说:

The ::first-line CSS pseudo-element applies styles to the first line of a block-level element.

但是当我写这个的时候:

p::before {content: 'Red text'; display: block;}
p::first-line {color: red;}
<p>This text shouldn't be red</p>

它在 Firefox 中不起作用(单词 'Hello' 不是红色)。这个有什么问题吗?

What's wrong with this one?

简单地说,这个行为没有问题。根据规范,Firefox 的行为也是正确的。


当第一行是 ::before::after伪元素时::first-line伪元素的行为在规范中有选择地显示[1]。所以难怪所有浏览器的行为都不一致。

§ 4.1. Generated Content Pseudo-elements: ::before and ::after[1]

As with the content of regular elements, the generated content of ::before and ::after pseudo-elements may be included in any ::first-line and ::first-letter pseudo-elements applied to its originating element.

此外,应用样式时的行为如 Selectors Level 3 中所写,与 Google Chrome[2][=68= 的行为相匹配].如果您不将样式应用于匹配元素,它的工作方式与 Firefox 类似。

7.4. The ::before and ::after pseudo-elements[2]

The ::before and ::after pseudo-elements can be used to describe generated content before or after an element’s content. They are explained in CSS 2.1 [CSS21].

When the ::first-letter and ::first-line pseudo-elements are applied to an element having content generated using ::before or ::after, they apply to the first letter or line of the element including the generated content.

举个例子,Google Chrome 和 Firefox 的区别在于 ::first-line 伪元素装饰是否应用于 ::before::after 伪元素-元素。

Google中的问题代码行为Chrome

Firefox 中的问题代码行为


要在 Firefox 中对 Google Chrome 做同样的事情,您可以将 color 属性 应用于 ::before 伪元素,如 在问题文本中。

p::before {
  content: 'Red text';
  display: block;
  color: red;
}
<p>This text should be red</p>