0

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
viery365
  • 935
  • 2
  • 12
  • 30
  • It seems to me that it's contained in a div with id of 'exp', so it has it's font-size multiplied by 0.8 and its colour set to red. At some point after, the h2 tag is applied. Again the font-size is multiplied by the supplied value - 0.9 this time (totalling 0.8*0.9 = 0.72). And again the supplied colour is applied, in this case, black. – enhzflep Nov 25 '15 at 10:49
  • Thank you!! This might be the answer!!!:) It was your words I was looking for:) Thank you again! – viery365 Nov 25 '15 at 10:56

1 Answers1

2

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>
Salman A
  • 262,204
  • 82
  • 430
  • 521