More specific CSS rule doesn't work

In my next code, I defined a more specific rule for h1 as #inner h1 and a less specific rule, since # container h1 is also defined. But if #container h1 is placed after #inner h1, then it takes effect, and #inner h1 is ignored until it should be, because it is more specific.

Please help me in understanding the problem.

CSS

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

HTML:

 <div id="container"> <div id="inner"> <h1>Hello World!</h1> </div> </div> 
+7
source share
3 answers

Maybe your idea of ​​specificity doesn't work a bit. Specificity should be a contextless idea: since CSS can be loaded independently of HTML, you don’t need an HTML document to guess which rule is more “specific”. Consider another example:

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

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

Point, both rules are visible with the same specificity ( h1 descendants of the element identified by id ), and the selector does not give higher priority to closer descendants.

If two rules of equal specificity are applied, the winner is the last declared in CSS.

+6
source

Both have the same specificity, and as you noticed, the order that they appear in the stylesheet is the determining factor for which style rules apply.

There are many ways to structure rules to get more specifics, but overall I would stay away from the !important modifier.

See 6.4.3 Calculating Selector Specificity in the W3 CSS Specification for more information.

+3
source

this is not a problem at all :) CSS analyzes the classes one by one, and the last rule redefines the previous one, of course, if the previous one is no more specific or does not include important instructions, you can put the font size: 25px! Important; in the first so that it overlaps the last rule, otherwise just change the places of the classes

-2
source

All Articles