覆盖特定html元素的CSS属性 [英] Overriding CSS properties for a specific html element

查看:102
本文介绍了覆盖特定html元素的CSS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下:

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

在我的样式表中,我有:

In my stylesheet I have:

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

我很高兴。现在,对于文章实例,我要执行以下操作:

The article is styled, and I am happy about it. Now, for a single instance of article, I want to do the following:

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

我已经定义:

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

但是类没有设置背景颜色。看起来,无论CSS样式表中的CSS规则的顺序如何,html标记文章的样式都优先。

But the class is not setting the background-color. It seems that the styling of the html tag article takes precedence, no matter the order of the CSS rules in my stylesheet.

如何使用样式类覆盖样式化html标记的CSS属性?这是可能吗?

How can I overwrite a CSS property of an styled html tag by using a styling class? Is this at all possible? Any alternative?

推荐答案

这是一个 CSS specific 问题。

That's a CSS specificity issue.

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

.main_section article has a higher specificity value than .special-bg selector.


内联样式> IDs > 类,属性和伪类> 元素类型和伪元素,因此这两个CSS选择器的Specificity的计算将是:

In terms of value: Inline Style > IDs > Classes, Attributes, and Pseudo-classes > Element Types and Pseudo-elements, So the calculation of Specificity of these two CSS selectors would be:

.special-bg

Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 0


$ b b

.main_section article

Inline Style    ID   (Pseudo-)Class    (Pseudo-)Element
0               0    1                 1

11 > > 10 => .main_section article selector wins!

11 > 10 => .main_section article selector wins!

您可以使用以下命令:

.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/

这是一个计算特异性值的好工具:

And a great tool to calculate the specificity value:

  • http://specificity.keegan.st/

这篇关于覆盖特定html元素的CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆