Shawn Taylor
Shawn Taylor

Reputation: 3969

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>

Upvotes: 8

Views: 3340

Answers (3)

zneak
zneak

Reputation: 138031

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.

Upvotes: 8

steveax
steveax

Reputation: 17753

Those both have the same specificity and as you note, the order they appear in the style sheet is the determining factor for which style rules are applied.

There are a variety of ways you could structure the rules to gain more specificity but in general I'd stay away from the !important modifier.

For more information see 6.4.3 Calculating a selector's specificity in the W3's CSS spec.

Upvotes: 3

Mr. BeatMasta
Mr. BeatMasta

Reputation: 1312

this is not an issue at all :) CSS parses classes one after another and the last rule overrides previous, of course if the previous is not more specific or does not include !important statements in it, you can put font-size: 25px !important; in the first so that it overrides the last rule, otherwise just change places of classes

Upvotes: -2

Related Questions