Search code examples
csscolorscss-specificity

CSS inheritance -- color property


Probably missing something really simple here as I am quite new to this -- but, I don't understand why, in the below code, the <a> and <h2> elements do not inherit the color property (white) from the .hero class. Simplified the code as much as possible.

The HTML:

<section class="hero container">
    <h2>A header!</h2>
    <p>Some stuff!!!</p>
    <a href="something.html">Linky</a>
</section>

The CSS:

a {
    color: #648880;
}

h2 {
    color: #648880;
}

.hero {
    color: #fff;
}

The result of this code is that the <p> element has text w/ color #fff, as specified in the .hero class -- which is as expected. However, the <a> & <h2> elements have color #6488880, as specified in the element selectors for <a> & <p>.

Same issue demonstrated in JSFiddle here

Shouldn't the .hero class's color attribute be overriding the color attribute in the element selectors? Am I completely misunderstanding specificity somehow? Of course I can use .hero a or .hero h2, but I don't see why I have to.


Solution

  • Why would you expect a property specified on a parent to override one specified on a child?

    Specificity refers to a way to prioritize rules selecting the same element. The specificity of a rule on a parent (.hero) has no relevance to the specificity of a rule on its children (a).

    In this case, the default color on the a element is inherit. However, you explicitly specified a different color. No amount of specificity or !important on the parent can cause it to override an explicit color specified on the child.