Why is my span blue instead of inheriting red from its parent?

拟墨画扇 提交于 2019-11-30 14:43:14

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;
}

Good question. The reason this happens, iiuc 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.

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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!