CSS Specificity

posted by Ishmael Sanchez on Oct 22, 2009

CSS Specificity is one of those things that you might assume you already have a firm grasp of since you are able to write solid CSS. Yet, CSS specificity is pretty confusing. It takes a little bit of time to get used to, but is well worth the effort. Have you ever created a CSS rule and wondered why it didn't apply to an element even though you thought it would? That my friend is CSS specificity owning you!

At its heart CSS specificity determines what CSS is applied by the web browser. There are many different specificity rules, for example:

  • If two selectors apply to the same element, the one with higher specificity wins
  • When selectors have an equal specificity value, the latest rule is the one that counts
  • A class selector beats any number of element selectors

So what does that all mean? Well, all selectors have a precedence level. There are four categories which define the precedence level (specificity) of a given selector: inline styles, ids, classes, and elements. Listed below are the categories and the associated value.

HTML elements: 1
Classes: 10
Ids: 100
Inline: 1000

You can find the specificity of any CSS rule by adding up your selectors. For instance:

#content .feature p

Equals 111, 100 for the #content, 10 for the .feature, and 1 for the p. The bigger the number the higher the specificity level. If you are writing proper CSS you shouldn't be dealing with any inline CSS. So then you are just left with ids, classes, and HTML elements. So you should be using ids in your CSS to increase specificity. This becomes really important when you are theming in Drupal because modules add classes everywhere. So when you are creating your styles, to override the module rules you need to have rules with higher specificity. Understanding this concept can help you create more efficient CSS which will save you time in the long run.


Post new comment

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.

Ishmael Sanchez