为什么 CSS 继承 属性 覆盖了我的风格?

Why the CSS inherit property overrides my style?

在下面的示例中,我有一个 Bootstrap 按钮样式,它被 Kendo-UI 的 .k-grid 设置的 color: inherit 条目劫持:

.k-grid a {
  color: inherit;
}
<div class="k-grid">
  <a class="btn btn-secondary" href="#">Button</a>
</div>

此处演示:http://jsfiddle.net/aq9Laaew/299912/

您可以观察到 .k-grid ainherit 属性 绕过了传递给 a 标签的任何其他 类。最终 Bootstrap 按钮在 Kendo 网格 table.

中显示错误的颜色

解决这个问题的正确方法是什么?我不确定在 Bootstrap 的 SASS 中添加 !important 是最好的解决方案。

我建议你了解 css 特异性 例如:http://cssspecificity.com

在你的情况下 .one-class 不如 .on-class 和一个元素

inherit CSS 关键字导致为其指定的元素从其父元素中获取 属性 的计算值。它可以应用于任何 CSS 属性,包括 CSS shorthand 所有。

对于继承的属性,这加强了默认行为,只需要覆盖另一个规则。

这将帮助您: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

如果您想深入了解: https://developer.mozilla.org/en-US/docs/Web/CSS/inherit , https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value

查看您的 fiddle 后,我可以在检查器中看到 Bootstrap 的重置应用了以下内容:a:not([href]):not([tabindex]) {color: inherit;}

除此之外,您 fiddle 中的锚点没有 href,因此上述 CSS 适用。

<link href="http://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="k-grid">
  <a href="#" class="btn btn-secondary">Button</a>

  <a class="btn btn-secondary">Button</a>
</div>

因此尝试使用以下方式设置您的按钮样式(没有 href): 由于 CSS specificity.

.btn-secondary {color: white;} 将无法工作

如果您仍然对 CSS specificity 感到困惑,请自己找一个特异性计算器,例如 这个 ,然后将两个选择器粘贴到其中。

您会发现 .btn-secondary 不够具体 无法覆盖来自 Bootstrap 为您的按钮应用样式的重置的规则。


鉴于 kendo-ui 也影响您的按钮样式:.k-grid a {color: inherit;},解决问题的最佳方法是将按钮定位为(您猜对了)更高特异性的选择器。

.k-grid a {
  color: inherit;
}

.btn.btn-secondary {
  color: white;
}
<link href="http://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="k-grid">
  <a href="#" class="btn btn-secondary">Button</a>

  <a class="btn btn-secondary">Button</a>
</div>