从不同文件加载时,是什么决定了两个元素之间的顺序 CSS 是 "specified"?

What determines the order CSS is "specified" between two elements when loaded from different files?

我正在帮助调试一个 CSS 问题,即两个相同的选择器在两个配置相同的服务器之间以不同的顺序加载。一条规则从页面中定义的样式表加载,另一条规则通过 Javascript 注入样式表文件加载。

根据级联规则,在我阅读它们时,应该归结为指定规则的顺序。问题似乎是竞争条件,但不清楚竞争条件的基础是什么。在 Chrome 的网络选项卡中,文件在两个服务器之间以相同的顺序列出;但是,当您深入到“元素”选项卡中的元素级别时,首先列出在给定服务器上优先的规则。

像这样加载时,是什么决定了两个元素之间 CSS 的 "specified" 顺序?

首先是选择器强度。

如果我使用架构,则为:
inline > identifier (100) > class (10) > tag (1) - 你可以计算括号中的 'points' 来找到选择器强度。

你可能知道。

现在,当你有两个相同强度的选择器,它们应用于一个元素时,例如。

#main p {color: red}
#top p {color: green}

和HTML

<div id=main>
    <div id=top>
        <p></p>
    </div>
</div>

段落将变为绿色,在开发工具中将被打上红色。两个selector实力相当,最新胜出。

另一个例子是:

#main #top p {color: red} /* will be red, stronger selector */
#main p {color: green}

在HTML中,主要因素是样式链接到文档的顺序,以及规则的顺序(直接在HTML或CSS中)。先加载哪个 CSS 文件并不重要(例如,由于文件大小),HTML 文档中的位置很重要。

如果选择器相同,则归结为顺序... CSS 和 DOM 中的顺序。那么,问题是,相对于原始的 <link>(或 <style>),您将动态生成的 <link>(或 <style>)放在哪里? DOM 中的顺序很重要。

如果您想确保首先评估动态创建的 CSS,请将其添加到 <head> 的顶部:

document.head.insertBefore(myLink, document.head.firstChild);

如果您希望最后评估它,请将其附加到 <body>:

document.body.appendChild(myLink);

最后评估的规则将被应用(禁止使用 !important

这是一个例子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      p {
        color: green;
      }
    </style>
  </head>
  <body>
    <p>test</p>  
    <script>
      (function() {

        var red = document.createElement("style");
        red.textContent = "p { color: red }";
        // We'll add this to the top of head. You'll never even notice because it will
        // be overridden by the existing green style.
        document.head.insertBefore(red, document.head.firstChild);

        var blue = document.createElement("style");
        blue.textContent = "p { color: blue }";
        // We'll add this to the end of the body after a three second delay. It will 
        // override the other styles.
        setTimeout(function() {
          document.body.appendChild(blue);
        }, 3000);

      })();
    </script>
  </body>
</html>