cssinheritancecss-specificity

Why doesn't my child element inherit color from its parent when parent has more specific selector?


Why in the following code world is blue rather than red?

The specificity of .my_class is 0,0,1,0, but it should inherit the color of #my_id whose specificity is higher at (0,1,0,0).

#my_id {
    color: red;
}
.my_class {
    color: blue;
}
<p id='my_id'>
    Hello
    <span class='my_class'>
        world
    </span>
</p>


Solution

  • See: w3c: 6 Assigning property values, Cascading, and Inheritance - 6.2 Inheritance

    An inherited value takes effect for an element only if no other style declaration has been applied directly to the element.

    This style applies to an element with id="my_id":

    #my_id {
        color: red;
    }
    

    ... and will apply (inherit) to an element nested within having class="my_class" only if its color property is otherwise unspecified.

    ...which no longer is the case once you declare:

    .my_class {
        color: blue;
    }