Search code examples
csscss-specificity

CSS Specificity: ID overwritten by class + element


So, my id selector with a colour !important is being overwritten by a simple .class h1 selector with no !important. I am baffled and unable to find any info on this.

I know about css specificity and no matter how I look at it, I would expect the h1 to be green even without the !important.

HTML:

<body id='id'>
  <div class='class'>
    <h1>Lorem ipsum</h1>
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</body>

CSS:

.class { color: black; }
.class h1 { color: red; }
#id { color: green !important; }

Demo: http://jsfiddle.net/TJ8tj/2/

I have tested this behaviour in latest Chrome, Safari and Firefox on OS X 10.9.1


Solution

  • Your .class h1 rule is applying a color directly to the h1 element itself, so it will never inherit the color from body. The !important only affects the body element because it is the one with the ID. It does not force child elements to inherit that value. Specificity also becomes irrelevant since your selectors are targeting different elements.

    In fact, the !important doesn't play any role in your code and so it should be removed.