CSS中可以单独使用伪元素吗?
Can pseudo-elements be used alone in CSS?
根据 W3C,选择器的定义不包括伪元素:
https://www.w3.org/TR/css3-selectors/#selector-syntax
上面link说:
A selector is a chain of one or more sequences of simple selectors
separated by combinators.
它还说:
A simple selector is either a type selector, universal selector,
attribute selector, class selector, ID selector, or pseudo-class.
关于如何使用伪元素,它说:
One pseudo-element may be appended to the last sequence of simple
selectors in a selector.
和
Only one pseudo-element may appear per selector, and if present it
must appear after the sequence of simple selectors that represents the
subjects of the selector.
那么这是否意味着伪元素只能作为 "valid" 选择器的后缀而不应该单独使用?
does that mean that a pseudo-element can only be a suffix to a "valid"
selector and should not be used alone?
你的结论是不正确的,因为universal selector*
可以省略
If a universal selector represented by *
[...] is immediately
followed by a pseudo-element, then the *
may be omitted and the
universal selector's presence implied.
所以你可以单独使用伪元素,例如::before
,因为在引擎盖下它将被视为 *::before
。
::before {
content: 'Hello!';
}
根据 W3C,选择器的定义不包括伪元素: https://www.w3.org/TR/css3-selectors/#selector-syntax
上面link说:
A selector is a chain of one or more sequences of simple selectors separated by combinators.
它还说:
A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.
关于如何使用伪元素,它说:
One pseudo-element may be appended to the last sequence of simple selectors in a selector.
和
Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector.
那么这是否意味着伪元素只能作为 "valid" 选择器的后缀而不应该单独使用?
does that mean that a pseudo-element can only be a suffix to a "valid" selector and should not be used alone?
你的结论是不正确的,因为universal selector*
可以省略
If a universal selector represented by
*
[...] is immediately followed by a pseudo-element, then the*
may be omitted and the universal selector's presence implied.
所以你可以单独使用伪元素,例如::before
,因为在引擎盖下它将被视为 *::before
。
::before {
content: 'Hello!';
}