Search code examples
csscss-specificity

Why color and font-size properties got different treatments on specificity?


I have this CSS:

h2 {
  color: #000;
  font-size: .9em;
}
#exp {
  color: red;
  font-size: .8em;
}
<div id="exp">
  hello
  <h1>hello</h1>
  <h2>hello</h2>
  <h3>hello</h3>
</div>

The result is this:

enter image description here

I understand the changing on the font-size. #exp is more specific than h2, but why didn't the color change?


Solution

  • Specificity counts when one element is matched by two rules; in which case the rule with higher specificity wins. However, this is not the case in your example; the rule #exp { } does not match h2 elements.

    Here is how the rules in your example work:

    /* rule #1 */
    h2 {
      color: #000;
      font-size: .9em;
    }
    /* rule #2 */
    #exp {
      color: red;
      font-size: .8em;
    }
    <div id="exp">
      hello           <!-- red color (via rule #2) -->
      <h1>hello</h1>  <!-- red color (inherited from parent) -->
      <h2>hello</h2>  <!-- black color (via rule #1) -->
      <h3>hello</h3>  <!-- red color (inherited from parent) -->
    </div>