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

4

8

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>
Atbara answered 23/6, 2010 at 1:34 Comment(0)
W
4

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;
}
Wong answered 5/10, 2012 at 21:14 Comment(1)
Seems like if a child got affected by styles inside a *, the child also ignores its parent's styleTobar
C
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.

Confidante answered 7/4, 2011 at 4:38 Comment(0)
J
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

Jetliner answered 23/6, 2010 at 1:35 Comment(0)
C
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).

Carmoncarmona answered 23/6, 2010 at 1:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.