CSS 个具有相同特异性的标签选择器的特异性顺序

Specificity order of CSS tag selectors with equal specificity

在更新我对 HTML 和 CSS 的基础知识的同时,我研究了 W3 website, as well as Mozilla.org 和几个教程网站上概述的特异性规则。但是,其中 none 似乎可以解释我在这里遇到的行为。

h1{
    color: blue;
}

body{
    color: yellow
}

div{
    color: red;
}
<html>
<head></head>
<body>
    <div>
        <h1>This is the title</h1>
    </div>
</body>
</html>

无论上面显示的 CSS 规则的顺序如何,h1 始终变为蓝色。注释掉 h1 规则时,无论顺序如何,h1 始终变为红色。这显然表明应用这些规则的优先级是 h1 > div > body.

虽然这很直观,但毕竟 h1 比选择整个 body 更具体,它们的 'formal' 特异性应该完全相同 (0,0,1)根据 Mozilla.org.

'Source order' 应应用规则

如果我在这里解释有误,谁能帮我解释一下?在我看来,源顺序似乎表明上面的代码应该以红色显示标题。尽管我同意当前的行为可能更直观(h1 看起来比 div 更直观),但如果有人能指出这些的正式定义的方向,我会非常高兴规则,因为特异性规则似乎没有充分解释这一点。

当两个或多个选择器匹配同一个元素时,特异性很重要——这里不是这种情况。

例如: 在下面的示例中,更具体的选择器 div#id.class 不会胜过 h1 因为它们指的是两个不同的元素,所以 h1 的颜色由第一条规则 [=15] 决定=]

h1{
    color: blue;
}

   
div#id.class {
    color: red;
}
<html>
<head></head>
<body>
    <div id="id" class="class">
        <h1>This is the title</h1>
    </div>
</body>
</html>

重要的不是标签,而是 DOM 中最近的节点。

h1{
    color: blue;
}

body{
    color: yellow
}

div{
    color: red;
}
<html>
<head></head>
<body>
    <h1>
        <div>
            This is the title
        </div>
    </h1>
</body>
</html>