Overriding CSS properties for a specific html element

拈花ヽ惹草 提交于 2019-12-28 02:13:26

问题


I have the following:

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

Which I have defined:

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

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.

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


回答1:


That's a CSS specificity issue.

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

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

.main_section article

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

11 > 10 => .main_section article selector wins!

You could use the following:

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

Further reading:

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



回答2:


You can use this css

.main_section .special-bg{

  background-color: #276a7f !important;

}



回答3:


Use this instead:

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

see this fiddle for example: http://jsfiddle.net/Ckxsw/

Something like this would be a useful read: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/




回答4:


You could use !important, like this:

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


来源:https://stackoverflow.com/questions/21329824/overriding-css-properties-for-a-specific-html-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!