Search code examples
htmlcsscss-selectorscss-specificity

!important overriden by a class of child element


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


Solution

  • 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 !importantwhenever 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