CSS Best Practice #4: Understand Selector Specificity for Better Speed and Easier Override

Understanding the specificity of CSS selectors is important because it makes overriding your previous styles easier. The fastest to slowest selectors also corresponds to how easy it will be to override the cascaded and/or inherited style rules.

Selectors: Fast to Slow

Jon Sykes did some CSS performance testing and the results show which selectors were fast/slow. You can check out his post for his approach, which includes a zip file of the html files he used. Just so you know, there\’s probably more testing to be done, such as testing pseudo-classes and different combination\’s of selectors. I\’ll just give you the summary of his results, from fastest to slowest.

  1. Tag – a
  2. Class – .class
  3. Descender – div div div p a.class
  4. Child – div > div > div > p > a.class

Selectors: Specificity

Remember the saying: \”Less is more\” because that is the case here. Sitepoint\’s CSS Reference\’s definition:

Specificity is a mechanism within the CSS cascade that aids conflict resolution. The concept of specificity states that when two or more declarations that apply to the same element, and set the same property, have the same importance and origin, the declaration with the most specific selector will take precedence.

So when we compare specificity to Jon\’s results, the more specific the selector, the slower it is. I also find that the more specific selectors takes up more time and keystrokes.

For example, I have this HTML to style:


Example Styles 1.
Say I want to style the headlines in that story list. The general style is short, thus it SHOULD be fast. The override is a little longer so it\’s a little slower.

/* General style to start */
.story_list a {font-size:14px; font-weight:bold;}

/* Override style */
.latest_news .story_list a.headline {font-size:12px;}

Example Styles 2.
The following styles the same HTML above, but they are much longer.

/* General style to start */
div .box .story_list li .info a {font-size:14px; font-weight:bold;}

/* Override style */
div.latest_news .box .story_list li .info a.headline {font-size:12px;}

When you compare styles #1 and styles #2, you\’ll notice that #1 is easier to override because it\’s short. #2 takes a few more class names before it can override the general styles.

Conclusion

So what I\’m saying is to keep things short and sweet. It will be easier to override when your stylesheet becomes complex. It will be faster too.

One thought on “CSS Best Practice #4: Understand Selector Specificity for Better Speed and Easier Override”

Leave a Reply

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