:nth-of-type 选择器覆盖所有其他 CSS 选择器

:nth-of-type selector overrides all other CSS selectors

我正在尝试复习 HTML、JavaScript 和 CSS3 的考试;我对 CSS 选择器和优先选择器有点困惑。

我有以下 CSS:

table                   { border: 1px solid black; }
tr:nth-child(odd)       { background-color: red; }
tr td:nth-of-type(even) { background-color: blue; }
td                      { background-color: green; }

我认为最后出现的优先,所以在我看来 table 中的所有单元格都是绿色的。

然而,根据第 n 个类型选择器,偶数单元格仍然是蓝色的。即使我把它放在顶部并移除绿色的 td 线,蓝色仍然显示在中间,只有奇数单元格显示为红色。

有人可以解释为什么第 n 个类型似乎优先于其他所有类型吗?

示例如下:

table { border: 1px solid black; }
tr:nth-child(odd) { background-color: red; }
tr td:nth-of-type(even) { background-color: blue; }
td { background-color: green; }
<table style="width: 100%;">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

https://jsfiddle.net/e6157xwz/

蓝色的规则更具体,这就是它优先的原因。

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

这与顺序无关,与准确性有关。 第一个选择器是一个类型的选择器,第二个选择器是一个类型的选择器然后指定一个过滤器,第三个选择器指定两个类型和一个过滤器。

选择器越准确,优先级越高。声明顺序仅在两个(或更多)选择器均等准确时才重要。

这是因为 specificity of your selectors. There are two rules that match td elements. Their calculated specificity 是:

tr td:nth-of-type(even) -> 0,0,1,2
td                      -> 0,0,0,1

无论源顺序如何,具有更高特异性的规则将获胜。

这是什么?

这里发生的事情是selector specificity

The following list of selector types is by increasing specificity:

  1. Universal selectors (e.g. *)
  2. Type selectors (e.g. h1)
    Class selectors (e.g. .example)
    Attribute selectors (e.g. [type="radio"])
  3. Pseudo-classes (e.g., :hover)
  4. ID selectors (e.g. #example)
  5. Inline style (e.g. style="font-weight:bold")

代码的简化说明

在您的示例中,伪选择器 :nth-of-type(even/odd) 是优先的类别 3,因为并发选择器仅为 type selectors(类别 2.1)。

重要提示

与 link 背后可用的 MDN 信息不同,我已更正该类型,class 和属性选择器实际上具有相同的特异性。