CSS 覆盖,首先加载样式 sheet 以先例

CSS override, first loaded style sheet taking precedent

我有一个非常奇怪的问题,我无法用我的 css 样式表弄清楚。我有 2 个样式表,一个来自 cdn,一个被缩小然后注入到我的本地开发服务器上的 index.html(本地)。所以只是为了快速参考,在我的 header 中我有这样的东西:

<link rel="stylesheet" href="myCDNStyleSheet.css">
<!-- injector:css -->
<link rel="stylesheet" href="css/localMinifiedStyles.css?1474574347809">
<!-- endinjector -->

所以这只是使用带有 grunt-cssmingrunt-injector 的 grunt 任务来放置带有它自己的哈希的样式表。

现在奇怪的是,即使 myCDNStyleSheet 首先加载,它的一些样式会优先于 localMinifiedStyles 中的样式,所以目前,我不得不放一些!important 关于 'localMinifiedStyles' 中的样式,这对我来说很奇怪。

所以非常清楚,我的意思是:

myCDNStyleSheet.css 有 :

  .styleMe {
      margin-left: 5px
  }

localMinifiedStyles.css有:

 .styleThis {
     margin-left: 12px
 }

渲染后的 html 看起来像:

 <div class="styleMe styleThis"> 

正在使用 margin-left: 5px 而不是 12。我可以在检查器中看到它们。

交换它们的加载顺序并不能解决这个问题,事实上它进一步破坏了它,因为 localMinifiedStyles 中有一些样式正确地获得了优先权。

即使在 chrome devtools 中检查样式,我也看到 localMinifiedStyles 位于占优势的样式下方。我不知道这是什么原因,是否有可能是 grunt 注入做了一些我不知道的事情?到目前为止,我在使用 css 时的假设是最后加载的样式表优先,我在这里遗漏了什么?

我真的不确定是什么导致了你描述的行为(如果你有完全相同的 "priority" 和 css 规则 - 后者会赢),但是一个简单的方法来修复你的问题是在 css 定义中复制 class。如果你想让 styleThis class 接管你可以使用:

.styleThis.styleThis {
    margin-left: 12px;
}

这有点像 hack,但它适用于 chrome、firefox 和 ie 的最新版本。

.green.green {
  color: green;
}
.red {
  color: red;
}
<div class="red green">
  This text's color should have been red because the red rule is latter in the CSS, however it will be green due to the <code>.green.green</code> in the css rules.
</div>