你如何确定是什么压倒了你的风格?

How do you determine what is overriding your style?

在摆弄示例代码的样式时,我发现代码中的样式会覆盖我的样式,因为它们会使用更高优先级的引用(例如:.div .class > .class)。

我会遇到这样的情况:

我如何找出哪种风格覆盖了我的风格? 我想避免使用 !important 因为最终我会遇到同样的情况。

编辑:我不是在问为什么会这样。我已经知道优先级,因此我提到 .div .class 的优先级高于 .class。我想追踪实际使用的是什么,而不是简单地告诉我它是 "inactive"。另外,我已经知道 Chrome Developer,因为屏幕截图来自 Chrome Developer。

编辑:实际问题已解决,但问题仍然存在...是否有更简单的方法来查看导致覆盖的原因?

修复:我只需要正确顺序的选择器。先是.box,然后是.box-blue

有一些浏览器扩展可以帮助解决这个问题。我在 Firefox 中使用 "Web Developer",但还有很多其他的。

Chrome 还有查看 > 开发人员 > 开发人员工具。

如果您将鼠标悬停在屏幕上的某个项目上,他们会告诉您它的路径 (html > body > div.blah > span.foo) 以及 css 样式是什么应用于该项目。

这里简单解释一下。

例如某些选择器将覆盖现有选择器

p {
  color: green;
}
.Paragraphs {
  color: yellow;
}
#paragraph2 {
  color: red;
}
<p>Lorem Ipsum</p>
<p class="Paragraphs">Lorem Ipsum</p>
<p id="paragraph2" class="Paragraphs">Lorem Ipsum</p>
<p class="Paragraphs" style="color: blue">Lorem Ipsum</p>

如图所示,选择器 p 被选择器 .Paragraphs 覆盖,选择器 #paragraph2 覆盖 .Paragraphs,样式属性覆盖 #paragraph2,当然任何带 !important 的选择器都会覆盖大部分内容。

您可以在上述示例中使用的开发工具中向上或向下滚动样式选项卡,以找到覆盖 .box-blue 的选择器。一旦您在另一种样式中找到启用的 border-color,您就可以确定覆盖它的选择器。

例如,当您使用 border-color: red 设置 .box-blue 样式时,它可能会被具有可能相同 属性、border 的另一种样式覆盖。因为 border: 1px solid blue 可能是 shorthand for border-width: 1px + border-style: solid + border-color: blue,那么它可能是覆盖以前的样式。

没有确定的方法来推断哪个选择器覆盖了给定的样式(据我所知),但是开发工具界面非常直观,通常很容易解决。

您的覆盖样式显示时带有删除线。要找出哪个选择器覆盖了它,请查找相同规则的未击中版本。

有时候这就像看到一样简单:

color: red;

并且必须寻找一个选择器:

color: blue;

Chrome 开发工具实际上按优先级对选择器进行排序,因此如果您发现被覆盖的样式,您可以保证覆盖将在同一个选择器中或在它上面的选择器之一中。

但您必须记住,有些规则是由其他规则组成的,您不会总能找到同名的相应规则。在您的示例中,您的 border-color 规则被上述选择器中的 border 规则覆盖。边界规则是 shorthand 用于指定 border-widthborder-styleborder-color

在您的图像中,您可以看到 .box-blue class 的 border-color: #bce8f1 规则已被 border: 1px solid transparent 覆盖(我看不到选择器)。您可以在检查工具的选择器右侧看到 CSS 个被覆盖 CSS 规则的文件。

有时 CSS 规则可能会被 JavaScript 更改。它可能显示为内联 CSS.

在 devtools 的样式检查器中,选择 Computed。找到您感兴趣的 属性 并单击它。您将看到适用于此 属性 的所有规则的列表,活动规则位于顶部,每个规则都有一个 file/line 对其定义位置的引用。

考虑以下 HTML:

<style>
  #foo { color: red; }
  p    { color: blue; }
</style>

<p id="foo">What color am I?</p>

您会看到以下内容:

在 Firefox Developer Tools 中,您可以在检查器中覆盖的 属性 附近单击一下找到它:

Overridden declarations

Starting in Firefox 43, overridden declarations have a magnifying glass next to them. Click the magnifying glass to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given property.

This makes it easy to see which rule is overriding the declaration:

https://www.youtube.com/watch?v=i9mDVjJAGwQ

这是它的样子。观看视频以了解实际效果。