Search code examples
htmlcsscss-selectorscss-specificity

More specific CSS rule is not working


In my following code, I have defined more specific rule for h1 as #inner h1 and less specific rule as #container h1 is also defined. But if #container h1 is put after #inner h1 then it takes effect and #inner h1 is ignored while it shouldn't be because its more specific.

Please help me in understanding the issue.

CSS:

#inner h1 { font-size:25px; }
#container h1 { font-size:15px; }

HTML:

<div id="container">
  <div id="inner">
    <h1>Hello World!</h1>   
  </div>
</div>

Solution

  • It might be that your idea of specificity is a little off. Specificity has to be a context-free idea: since CSS can be loaded independently of HTML, you must not need an HTML document to guess which rule is more "specific". Consider this other valid example:

    <div id="inner">
      <div id="container">
        <h1>Hello World!</h1>   
      </div>
    </div>
    

    With this snippet, you would have to go against your initial guess that inner should be more specific. This means that your interpretation required context (which CSS does not have).

    The point is, both rules are seen with equal specificity (h1 descendants of an element identified by an id), and the selector doesn't give higher priority to closer descendants.

    In case two rules of equal specificity apply, the winner is the last one declared in the CSS.