Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!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

like image 668
Jaroslav Loebl Avatar asked Dec 25 '22 18:12

Jaroslav Loebl


2 Answers

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

like image 170
connexo Avatar answered Dec 29 '22 09:12

connexo


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.

like image 36
Vikram Deshmukh Avatar answered Dec 29 '22 09:12

Vikram Deshmukh