Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

Overriding CSS properties for a specific html element

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

And a great tool to calculate the specificity value:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...