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>
The color property is also inherited. Inheritance in CSS occurs when an inheritable property is not set on an element. It goes up in its parent chain to set the property value to its parent value. CSS properties such as height , width , border , margin , padding , etc.
Answer. When you dive into our CSS course you will learn that child elements inherit most of their styling from their parent elements. In other words, most styles cascade down from parents to children.
Only Certain Properties are Inherited The same is true in CSS; not every CSS property is inherited by default by child elements. In fact, if all properties were inherited, the effect would be similar to having no inheritance at all and you would have to write a lot of CSS to override this behavior.
You can add multiple classes to a single DOM element, e.g. Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails. Inheritance is not part of the CSS standard.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With