【问题标题】:Why the CSS inherit property overrides my style?为什么 CSS 继承属性会覆盖我的样式?
【发布时间】:2018-12-25 18:13:24
【问题描述】:

在以下示例中,我有一个 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 Button 在 Kendo-grid 表格中显示为错误的颜色。

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

【问题讨论】:

  • 请发minimal reproducible example,以便我们进行实验和调试。
  • 因为 CSS 意味着 CascadeStyleSheet。而.k-grid a.btn-sm 具有更大的“价值”。更多选择器 = 更多价值
  • 在 CSS 中,有一个“值”取决于此样式在“外部文件/内联/嵌入(
  • @csmckelvey 我用一个最小、完整和可验证的例子编辑了我的问题。

标签: css twitter-bootstrap kendo-grid css-specificity


【解决方案1】:

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

最重要的是,您的小提琴中的锚点没有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 感到困惑,请为自己找一个像 this one 这样的特异性计算器,然后将两个选择器都粘贴进去。

您会发现 .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>

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • @Laurent 谢谢你的回答。我已阅读您的链接并编辑了我的问题。
    【解决方案3】:

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

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

    这会帮助你: 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-13
      • 2011-04-09
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2021-11-12
      相关资源
      最近更新 更多