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>
As a special case for increasing specificity, you can duplicate weights from the CLASS or ID columns. Duplicating id, class, pseudo-class or attribute selectors within a compound selector will increase specificity when overriding very specific selectors over which you have no control.
Since the third rule (C) has the highest specificity value (1000), this style declaration will be applied.
To fix this, we must increase the specificity values of the CSS selectors in the media query. If we make it so that the CSS selectors that target the same HTML elements have equal specificity, then the browser will follow the source order rule.
ID selectors have the highest specificity amongst the CSS selectors: 1, 0, 0, 0. Because of the unique nature of the ID attribute definition, we are usually styling a really specific element when we call up the ID in our CSS. – The specificity is 1, 0, 0, 1 because we have a type selector and an ID selector.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With