How To Make a Web Site the Modern Way. Part 13: The Cascade/CSS Specificity

One of the most important things in CSS is understanding the way rules are inherited and applied in the browser. This is one of those things that many developers “get” intuitively but don’t necessarily understand at a granular level.

There’s actually an algorithm, so if you’re stumped, you can actually count it out. It works like this:

  • First, find all rules that apply to the target element/property. This will be some combination of browser default > style sheet default > targeted rules. One easy way to visualize this is to look at the “styles” tab in Firebug.

    That view encompasses the latter two parts (style sheet default > targeted rules.) The first part (the browser default), is in effect an ancestor of the (otherwise, root) HTML element.

  • Once all the rules are gathered calculations are made to decide which ones are to be followed and which ones are to be discarded.That works like this:
    1. Sort by explicit weight- ‘!important’ rules carry more weight than normal declarations.
    2. Sort by origin: the author’s style sheets trump the browser default values.
    3. Sort by specificity of selector. More specific selectors trump more general ones. The formula is as follows:
      1. factor in any inline styles
      2. count the number of ID attributes in the selector
      3. the number of CLASS attributes in the selector
      4. the number of tag names in the selector

      Some examples:

      Selector # of INLINE RULES # of IDS #of CLASSES # of TAGS Specificity
      LI 0 0 0 1 0,0,0,1
      UL LI 0 0 0 2 0,0,0,2
      DIV UL LI 0 0 0 3 0,0,0,3
      DIV UL .red 0 0 1 2 0,0,1,2
      #myLI 0 1 0 0 0,1,0,0
      <p style="color:blue"> 1 0 0 0 1,0,0,0
    4. Sort by order specified: if two rules have the same weight, the latter specified wins. Rules in imported style sheets are considered to be before any rules in the style sheet itself.

If two rules only impact one column, the higher number wins. If the selector cuts across more than one column, the biggest numbers in the farthest most left column wins. So, inline styles (which you should avoid) are more specific than an ID, which, in turn is more specific than a class, which itself will trump a tag. If you can wrap your head around these concepts, you’ll go a long way towards making sense of CSS and how the rules are applied.


Leave a Reply

Your email address will not be published. Required fields are marked *