覆盖特定html元素的CSS属性

dan*_*ast 3 html css css-specificity

我有以下内容:

<section class="main_section">
    <article>
    ...
    </article>
</section>
Run Code Online (Sandbox Code Playgroud)

在我的样式表中,我有:

.main_section article {
    background-color:#fff;
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

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

<section class="main_section">
    <article class="special-bg">
    ...
    </article>
</section>
Run Code Online (Sandbox Code Playgroud)

我已经定义了:

.special-bg {
    background-color: #276a7f;
}
Run Code Online (Sandbox Code Playgroud)

但是课程没有设置背景颜色.似乎html标记的样式article优先,无论样式表中CSS规则的顺序如何.

如何使用样式类覆盖样式化html标记的CSS属性?这是可能吗?还有其他选择

Has*_*ami 7

这是一个CSS特异性问题.

.main_section article具有比.special-bg选择器更高的特异性值.

按价值计算: Inline Style> IDs> Classes, Attributes, and Pseudo-classes> Element Types and Pseudo-elements,因此这两个CSS选择器的特异性的计算是:

.special-bg

Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 0
Run Code Online (Sandbox Code Playgroud)

.main_section article

Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 1
Run Code Online (Sandbox Code Playgroud)

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

您可以使用以下内容:

.main_section .special-bg {
  /* Styles goes here... */
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

并且是计算特异性值的好工具: