CSS Specificity and You

TLDR: Calculating specificity is faster than guess and check when styling a page. Read on to see what this means.

The de facto standard of guess and test when styling elements on a page has always bugged me. Because of this, I whined to a coworker today that I wish there were straightforward rules for defining which css selector “wins” when it comes to styling. After a moment of said coworker’s fingers on the keyboard yielded four simple rules for defining this (reference below):

  1. Inline styles (Presence of style in document).
    • An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g.
    • These are worth 1000 in calculating the specificity of a given selector.
  2. IDs (# of ID selectors)
    • ID is an identifier for your page elements, such as #div.
    • These are worth 100 in calculating the specificity of a given selector.
  3. Classes, attributes and pseudo-classes (# of class selectors).
    • This group includes .classes, [attributes] and pseudo-classes such as :hover, :focus etc.
    • These are worth 10 in calculating the specificity of a given selector.
  4. Elements and pseudo-elements (# of Element (type) selectors).
    • Including, for instance, :before and :after.
    • These are worth 1 in calculating the specificity of a given selector.

So, for example, if we had this:

it would be worth 100 for the Id, 10 for each class, and 1 for the element name (a). In total, this is 121.

When compared to this:

the first one wins, because this is worth 31 (two real classes + one pseudo-class (:hover) + one element name).

A full explanation is here, for reference. I wish I had read this five and a half years ago, when it was first posted.

Incidentally, because of the valuation convention (1000, 100, 10, 1) and the beauty of base 10 arithmetic, we can just count the number of instances of each value level and concatenate them all together in order. E.g:

has 0-1000′s, 1-100, 2-10′s, and 1-1. Therefore, this is 0121, or 121 (just as it was when calculated with addition above).

Leave a Reply

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

× nine = 72

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">