我有以下几点:

<section class="main_section">
    <article>
    ...
    </article>
</section>

在我的样式表中,我有:

.main_section article {
    background-color:#fff;
    /* ... */
}

这篇文章有风格,我很高兴。现在,对于 article 的单个实例,我想执行以下操作:

<section class="main_section">
    <article class="special-bg">
    ...
    </article>
</section>

我已经定义了:

.special-bg {
    background-color: #276a7f;
}

但是该类没有设置背景颜色。似乎 html 标签 article 的样式优先,无论我的样式表中 CSS 规则的顺序如何。

如何使用样式类覆盖样式化 html 标记的 CSS 属性?这是可能吗?有什么替代方案吗?

最佳答案

这是 CSS specificity 问题。
.main_section article.special-bg 选择器具有更高的特异性值。

在值(value)方面:Inline Style > IDs > Classes, Attributes, and Pseudo-classes > Element Types and Pseudo-elements ,所以这两个CSS选择器的Specificity的计算是:
.special-bg

Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 0
.main_section article
Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 1

11 > 10 => .main_section article 选择器获胜!

您可以使用以下内容:

.main_section .special-bg {
  /* Styles goes here... */
}

进一步阅读:
  • http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
  • http://reference.sitepoint.com/css/specificity
  • http://cssspecificity.com/

  • 还有一个很好的工具来计算特异性值:
  • http://specificity.keegan.st/
  • 关于html - 覆盖特定 html 元素的 CSS 属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21329824/

    10-09 16:48
    查看更多