CSS 不覆盖样式

CSS doesnt overwrite style

我有 2 个样式表文件,style.css 和 index.css,它们正在分别加载

1-style.css 2-index.css

在我的 style.css 我有这样的代码

#mainNav nav > a:hover span:before {
    background-color: transparent !important;
}

#mainNav nav a.darkBlue span:before {
        background-color: #17729a;
}

现在在我的 index.css

当我写

#mainNav .darkBlue span:before {
background-color: transparent;
}

它不起作用,我应该在最后写上 !important 才能让它起作用

但是当我以不同的方式编写选择器顺序时,就像我在 style.css 中使用的方式一样,它可以在没有 !important

的情况下工作

像这样

#mainNav nav a.darkBlue span:before {
    background-color: transparent;
}

为什么?

CSS 具有层次结构。如果您想覆盖某些样式,则必须使用相同的选择器或更具体的选择器。

示例:

a.selector { color: blue }
.selector { color: red }

颜色不会改变。

但是

.selector { color: blue }
a.selector { color: red }

会把颜色改成红色,因为你的TAG和class选择器的组合更具体。

你有一个叫做 CSS 特异性的东西:

https://www.w3schools.com/css/css_specificity.asp

关于先到先得和具体顺序的非常好的读物:检查https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/ 请注意,这是一篇很长的文章。大多数人甚至对这能走多远一无所知。

Simply put: If two CSS selectors apply to the same element, the one with higher specificity wins.

这就是我遵循 BEM 方法的原因,这样可以避免此类麻烦。

您的声明是根据它们具体的程度来应用的。

根据 MDN - Specificity:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied.

Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector.

上面的link也涉及到决定特异性的因素:

The following list of selector types increases by specificity:

  1. Type selectors (e.g., h1) and pseudo-elements (e.g., ::before).

  2. Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).

  3. ID selectors (e.g., #example).

Universal selector (*), combinators (+, >, ~, ' ') and negation pseudo-class (:not()) have no effect on specificity. (The selectors declared inside :not() do, however.)


CSS 根据一些条件选择要应用的规则。给定应用于同一元素的规则,它们按以下顺序考虑:

1。 !important

span { color: red; }               /* base */
#mySpan { color: blue; }           /* specific  */
span { color: green !important; }  /* important */
<span id="mySpan" style="color: purple;">Example</span>

2。内联样式

span { color: red; }               /* base */
#mySpan { color: blue; }           /* specific  */
<span id="mySpan" style="color: purple;">Example</span>

3。特异性

span { color: red; }               /* base */
#mySpan { color: blue; }           /* specific  */
<span id="mySpan">Example</span>

4。最后声明

span { color: red; }               /* base */
span { color: yellow; }            /* last applied */
<span>Example</span>


通常最好尽可能避免使用 !important。如果您粗心地乱扔它们,有时您 实际上 需要覆盖一个,但您已经使用了最高优先级。