I have a very bad CSS rule (high specifity, use of !important) which sets color of text in a paragraph:
#wrapper .article .text {
color: green !important;
}
Then I put a simple span element in that paragraph and set color of the span text via simple class:
.black {
font-weight: bold;
color: black;
}
How come, that this simple class with low specifity and no !important flag overrides the parent rule?
Full snippet on codepen.io here: http://codepen.io/Jarino/pen/oXYeQZ?editors=110
This is simply because there is no more specific rule for that <span>
than what you have declared in .black
. Even though it is a child element of the <p>
that has an important!
flagged rule, it only inherits the color from it if it can find no more specific other color definition. Inheritance from a parent context is the least specific "rule" possible. Also, the !important
part of a rule is not inherited, afaik.
If this were not the case, you would be very commonly forced to either use !important
whenever an element takes a style that it already inherited from the parent, or you would have to constantly use very long selectors to make sure your child element selector does not have a lower specificity than the definition it inherits.
Also, compare what Mozilla says on the subject:
Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#directly-targeted-elements
The high-specificity rule applies only to the parent class. When it comes to it's children, the high-specificity of the parent class mellows down to a parent style that is inherited by the child.
And, when it comes to styling the child, all CSS rules specifically targeting it get precedence over the high-specificity rule of the parent.
If you do 'Inspect Element' for this child span tag in the Developer Console of your browser, you'll see how preference is given to CSS rules targeting that particular element that overrides all the parent styling that appears way down the list.
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