在 CSS 中,'div:first-of-type[label="hello"]' 与 'div[label="hello"]:first-of-type' 不同吗?

In CSS, is 'div:first-of-type[label="hello"]' different from 'div[label="hello"]:first-of-type'?

在 CSS 中,这个选择器是:

div:first-of-type[label="hello"]

任何不同于:

div[label="hello"]:first-of-type

?

与伪元素不同,伪类可以出现在select或:

的中间

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). ref

所以两者是一样的

div[label="hello"]:first-of-type {
  height:50px;
}


div:first-of-type[label="hello"] {
  border:5px solid;
}
<div label="hello" class="box"></div>


考虑the new specification

Like other simple selectors, pseudo-classes are allowed in all compound selectors contained in a selector, and must follow the type selector or universal selector, if present.


值得注意的是 :first-of-type 只会考虑元素及其同级元素。所以第一个 selector 不会 select 第一个 div 有 label=hello 但第一个 div 如果它有 label=hello.

换句话说,select 元素必须符合这两个条件,这就是顺序无关紧要并且 select 或两者相同的原因。

您可以同时看到 select 或如下所示:

div[label="hello"]:first-of-type
(div) && (label="hello") && (first of type)
(div) && (first of type) && (label="hello")
div:first-of-type[label="hello"] 

相关:Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?