7

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>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

4 Answers4

3

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;
}
Faust
  • 15,130
  • 9
  • 54
  • 111
3

The reason this happens is due to inheritance, not specificity.

Look at it this way, if the span didn't have that class, it would inherit the color red from the parent <p> element and "world" would be red. But note that that's due to inheritance.

When you set color for the span, via the class, that overrides the inherited value.

Specificity is for determining which rule to use in multiple competing rules. In your example, there are no competing rules for <span>, so specificity does not come into play. However, if you added this to your styles:

#my_id span {color: orange}

you would see that "world" is orange because of the specificity of the id being more than the class.

TylerH
  • 20,799
  • 66
  • 75
  • 101
ace105
  • 39
  • 1
2

It goes based on specificity and location. The class is applied directly to the text, but the ID is further away.

For a long explanation: http://monc.se/kitchen/38/cascading-order-and-inheritance-in-css

Aaron Butacov
  • 32,415
  • 8
  • 47
  • 61
2

A simpler way to think of it, specificity order applies at the same level, if a style is on a parent more local then it applies, regardless of if an ancestor has a style with higher specificity (since it's further away, or less-local).

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155