问题
Why in the following code world
is blue rather than red?
The specificity of .my_class
is 0,0,1,0
, but it inherits the color of #my_id
which specificity is higher (0,1,0,0
).
#my_id {
color: red;
}
.my_class {
color: blue;
}
<p id='my_id'>
Hello
<span class='my_class'>
world
</span>
</p>
回答1:
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;
}
回答2:
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.
回答3:
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
回答4:
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).
来源:https://stackoverflow.com/questions/3098349/why-is-my-span-blue-instead-of-inheriting-red-from-its-parent