外部 CSS !important override inline !important

External CSS !important overriding inline !important

我添加了一个 inline CSS 规则,用于从 div 中删除 padding-top 和 padding-bottom,该 div 由外部样式表添加 CSS 我无法修改使用 !important 的规则。 下面是我要修改的两个 div。

<div class="class1 class2 class3 class4">
<div class="class1 class5 class6">

我声明如下;

  .class2 {
    padding: 0 !important;
    padding-bottom: 0 !important;
    padding-top: 0 !important;
  }
  .class5 {
    padding: 0 !important;
    padding-bottom: 0 !important;
    padding-top: 0 !important;
  }

但是外部 CSS 文件正在加载此规则,覆盖了我的内联规则;

@media screen and (max-width: 767px) {
    .parent1 .parent2 .class1:first-child {
        padding-top: 17px !important;
    }
}
@media screen and (max-width: 767px) {
    .parent 1 .parent2 .class1:last-child {
        padding-bottom: 17px !important;
    }
}

为什么这会覆盖我的内联 CSS 规则?是不是任何内联规则(尤其是 !important)应该覆盖所有外部 CSS(即使是 !important)?根据我对特异性的理解,任何内联样式都具有两个数量级的特异性

(1, 1, 0, 1, 0)

比带有伪选择器的多亲

(1, 0, 0, 4, 0).

See here for documentation. Also here. And certainly here.

编辑:正如@myf 指出的那样,我对起源特异性值的理解似乎存在缺陷。内联 <style>[css rules]</style><link> css 文件具有相同的原始特异性值。因此,在我最初的 CSS 规则中,我的特异性低于 Squarespace 的。只有较高的起源特异性值。请阅读@myf 的回复,很有帮助。

我通过使用比 Squarespace 使用的父选择器更多的父选择器解决了这个问题。我最终使用了这个;

.parent1 .parent2 .parent3 .class {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
}

但我仍然不明白为什么这会奏效。特别是因为文档特别(明白了吗?)声明内联值在 "a, b, c, d, e" 特定顺序中持有 "b=1" 值,而每个父选择器只有一个额外的 "d=1" 值和 !important 值有一个 "a=1" 值。

供参考,特异性为

"!important 1/0 (if using=1, if not=0), inline 1/0 (if inline=1, if not=0), id (total #id usage), class/attrib/psuedo (total .class, [attrib], or :pseudo usage), element (total html body header main nav etc. usage)"

所以我的原始选择器(没有多个父项)等于

"1, 1, 0, 1, 0" (EDIT: I used <style>css</style> NOT <el style="css"> therefore the actual value is "1, 0, 0, 1, 0" because <style> rules have the same specificity value as external <link> stylesheets)

因为我正在使用 !important 所以 "a=1",使用内联 "b=1" EDIT: "b=0",不使用 ID "c=0",使用 1 class 选择器 "d=1", 没有使用元素选择器 "e=0"

Squarespace 选择器等于

"1, 0, 0, 4, 0,"

因为 !important "a=1",不是内联 "b=0",没有使用 ID "c=0",总共 4 class/pseudo 次使用 "d=4",没有使用元素选择器 "e=0".

因此我原来的选择器应该覆盖了 Squarespace 选择器。

而是等于

的新选择器

"1, 1, 0, 4, 0" EDIT: "1, 0, 0, 4, 0" see above edit

(见下文)是唯一有效的方法。

因为 !important "a=1",内联 "b=1",没有使用 ID "c=0",总共有四次 class 用法 "d=4",没有使用元素选择器 "e=0"

您显然混淆了源自 物理 HTML 属性 (<el style="[css declarations]">) 的 内联样式来源 页内样式 sheet 具有 "author" 级来源特异性并且源自 <style>[css rules]</style><link rel="stylesheet" href="[css file url]">.

页面中的样式和 link 元素在来源方面是相等的,属性在来源方面更具体。

不可能用作者[=]的!important规则击败内联原始级别(属性)的!important规则27=] 水平起源.