CSS Specificity: Things You Should Know

Advertisement

Apart from Floats1, the CSS Specificity is one of the most difficult concepts to grasp in Cascading Stylesheets. The different weight of selectors is usually the reason why your CSS-rules don’t apply to some elements, although you think they should have. In order to minimize the time for bug hunting you need to understand, how browsers interpret your code. And to understand that, you need to have a firm understanding on how specificity works. In most cases such problems are caused by the simple fact that somewhere among your CSS-rules you’ve defined a more specific selector.

CSS Specificity isn’t simple. However, there are methods to explain it in a simple and intuitive way. And that’s what this article is all about. You’ll understand the concept if you love Star Wars2. Really.

Let’s take a look at some important issues related to CSS Specificity as well as examples, rules, principles, common solutions and resources.

  • You can find the most important things you should know about CSS specificity in a brief overview at the beginning of the article.

CSS Specificity: An Overview Link

  1. Specificity determines, which CSS rule is applied by the browsers.
  2. Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
  3. Every selector has its place in the specificity hierarchy.
  4. If two selectors apply to the same element, the one with higher specificity wins.
  5. There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
  6. You can understand specificity if you love Star Wars: CSS Specificity Wars3.
  7. You can understand specificity if you love poker: CSS Specificity for Poker Players24184
  8. When selectors have an equal specificity value, the latest rule is the one that counts.
  9. When selectors have an unequal specificity value, the more specific rule is the one that counts.
  10. Rules with more specific selectors have a greater specificity.
  11. The last rule defined overrides any previous, conflicting rules.
  12. The embedded style sheet has a greater specificity than other rules.
  13. ID selectors have a higher specificity than attribute selectors.
  14. You should always try to use IDs to increase the specificity.
  15. A class selector beats any number of element selectors.
  16. The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
  17. You can calculate CSS specificity with CSS Specificity Calculator.

What is Specificity? Link

  • Specificity determines, which CSS rule is applied by browsers. “Specificity is a type of weighting that has a bearing on how your cascading style sheet (CSS) rules are displayed.” [Understanding Specificity75]
  • Selector specificity is a process used to determine which rules take precedence in CSS when several rules could be applied to the same element in markup. [Selector Specificity226]
  • Every selector has its specificity. “All rules in your CSS carry a specificity rating regardless of selector type, although the weighting that is given to each selector type varies and will ultimately affect the styling of your web documents.” [Understanding Specificity75]
  • If two selectors apply to the same element, the one with higher specificity wins.

Specificity hierarchy Link

  • Every selector has its place in the specificity hierarchy. There are four distinct categories which define the specificity level of a given selector:

    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. <h1 style="color: #fff;">

    2. IDs (# of ID selectors)
    ID is an identifier for your page elements, such as #div.

    3. Classes, attributes and pseudo-classes (# of class selectors).
    This group includes .classes, [attributes] and pseudo-classes such as :hover, :focus etc.

    4. Elements and pseudo-elements (# of Element (type) selectors).
    Including for instance :before and :after.

If you don’t know what exactly each of these terms stands for, you can take a look at the brief overview of them; in the last section of this article.

How to measure specificity? Link

  • Memorize how to measure specificity. “Start at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class or pseudo-class, add 1 for each element name or pseudo-element. So in
    body #content .data img:hover

    the specificity value would be 122 (0,1,2,2 or 0122): 100 for #content, 10 for .data, 10 for :hover, 1 for body and 1 for img.” [CSS Specificity8]

  • Alternative way: “Count the number of ID attributes in the selector (= a). Count the number of other attributes and pseudo-classes in the selector (= b). Count the number of element names and pseudo-elements in the selector (= c). Concatenating the three numbers a-b-c gives the specificity. [CSS Selector Specificity9]
  • CSS Specificity Wars – Cheat Sheet10
    To help me understand calculating specificity better I made a chart based on the following specificity (or Sith power) values. Each character (selector) is given its own Sith power (specificity value) depending on how powerful they are in the ways of the Dark Side. A storm trooper is less powerful than Vader who is in turn less powerful than the Emperor.
CSS Specificity Wars11

    Specificity Examples: Test Yourself Link

    It’s easier to calculate the specificity using the first method. Let’s find out, how it actually is done.

    1 * { } 0
    2 li { } 1 (one element)
    3 li:first-line { } 2 (one element, one pseudo-element)
    4 ul li { } 2 (two elements)
    5 ul ol+li { } 3 (three elements)
    6 h1 + *[rel=up] { } 11 (one attribute, one element)
    7 ul ol li.red { } 13 (one class, three elements)
    8 li.red.level { } 21 (two classes, one element)
    9 style=”” 1000 (one inline styling)
    10 p { } 1 (one HTML selector)
    11 div p { } 2 (two HTML selectors)
    12 .sith 10 (one class selector)
    13 div p.sith { } 12 (two HTML selectors and a class selector)
    14 #sith 100 (one id selector)
    15 body #darkside .sith p { } 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

    Specificity: Basic Principles Link

    • Equal specificity: the latest rule is the one that counts. “If you have written the same rule into your external style sheet twice, than the lower rule in your style sheet is closer to the element to be styled, it is deemed to be more specific and therefore will be applied.
      When selectors have an equal specificity value, such as

      #content h1 {
      padding: 5px;
      }
      
      #content h1 {
      padding: 10px;
      }

      where both rules have the specificity 0, 1, 0, 1, the latter rule is always applied.

    • Unequal specificity: the more specific rule is the one that counts. “A selector can contain one or more reference points, the greater the specificity rating of these reference points the more specific your rule is.” Browsers select the most specific rules to display. [Understanding Specificity1612]

    Specificity Rules Link

    • Rules with more specific selectors have a greater specificity. The more specific the references are in your selector, the greater the specificity for the rule. [Understanding Specificity13]
    • ID selectors have a higher specificity than attribute selectors. For example, in HTML, the selector #p123 is more specific than [id=p123] in terms of the cascade. Example: in
      A:
      a#a-02 { background-image : url(n.gif); }
      
      and
      
      B:
      a[id="a-02"] { background-image : url(n.png); }

      the first rule (A) is more specific than the second one (B). [W3C CSS 2.1 Specification14]

    • Contextual selectors are more specific than a single element selector. It also holds for other selectors involving more than one HTML element selector. [Cascade Inheritance15]
    • The embedded style sheet is closer to the element to be styled. So in the following situation

      CSS:

      #content h1 {
      padding: 5px;
      }

      (X)HTML:

      <style type="text/css">
      #content h1 {
      padding: 10px;
      }
      </style>

      the latter rule will be applied. [Understanding Specificity1612]

    • The last rule defined overrides any previous, conflicting rules. For example, given these two rules
      p { color: red; background: yellow }
      p { color: green }

      paragraphs would appear in green text. They would also have a yellow background however, because the first rule is not completely negated. [BrainJar.com17]

    • A class selector beats any number of element selectors. .introduction beats html body div div h2 p. [CSS Specificity for Poker Players24184]
    • The universal selector has a specificity of 0, 0, 0, 0. *, body * and similar selectors have a zero specificity. Inherited values also have a specificity of 0, 0, 0, 0. [CSS Specificity Clarified19]

    Specificity Example Link

    • Consider three code fragments:
      A: h1
      B: #content h1
      C: <div id="content">
      <h1 style="color: #fff">Headline</h1>
      </div>

      The specificity of A is 0,0,0,1 (one element), the specificity of B is 0,1,0,1 (one ID reference point and one element), the specificity value of C is 1,0,0,0, since it is an inline styling.

      Since

      0001 = 1 < 0101 = 101 < 1000,

      the third rule has a greater level of specificity, and therefore will be applied. If the third rule didn’t exist, the second rule would have been applied.

    Specificity in Practice Link

    • Use LVHA for link styling.
      “To ensure that you see your various link styles, you’re best off putting your styles in the order “link-visited-hover-active”, or “LVHA” for short.” [Link Specificity20]
    • Never use !important.
      “If you’re having specificity issues, there’s some quick ways to solve it. First, avoid !important.” “The !important declaration overrides normal declarations, but is unstructured and rarely required in an author’s style sheet.” [Understanding Specificity2321, Selector Specificity226]
    • Use id to make a rule more specific.
      Replacing a.highlight with ul#blogroll a.highlight changes the specificity from 0, 0, 1, 1 to 0, 1, 1, 2.
    • Minimize the number of selectors.
      “Use the least number of selectors required to style an element.” [Understanding Specificity2321]

    CSS Specificity Tools & Resources Link

    • CSS Specificity for Poker Players24184
      If you’re not from the programming world and CSS seems a bit confusing, perhaps this analogy may help clear some concepts up. Think of CSS rules as poker hands. The best hand determines an element’s style.
    • CSS specificity calculator
      Calculates the specificity of a given selector.
    • Understanding Specificity Tutorial25
      In this tutorial you will look at specificity. Specificity is a type of weighting that has a bearing on how your cascading style sheet (CSS) rules are displayed. All rules in your style sheet carry a specificity rating regardless of selector type, although the weighting that is given to each selector type varies and will ultimately affect the styling of your web documents.
    • Cascade Inheritance: Specificity26
      At this point it might be timely to have a quick discussion of specificity. Both inside a single style sheet, and in a cascade of style sheets, it should be clear that more than one rule can apply to the same element. What happens when two properties in separate rules which both apply to an element contradict one another?
    • CSS 2.1 Selectors Explained27
      An extensive overview of CSS 2.1 selectors. Learning how to use the full range of CSS selectors available in CSS 2.1 properly can actually help you keep your HTML a lot cleaner. It will let you minimise unnecessary use of the class attribute and the need for adding extraneous div and span elements to the markup.
    • CSS Specificity Bugs in IE28
      A brief overview of specificity bugs implemented in Microsoft Internet Explorer/Win.
    • CSS Structure and Rules29
      Basic Syntax, Pseudo-classes and Pseudo-elements, Cascading Order.
    • Specificity30
      It may not seem like something that important, and in most cases you won’t come across any conflicts at all, but the larger and more complex your CSS files become, or the more CSS files you start to juggle with, the greater likelihood there is of conflicts turning up.

    What is what? Link

    • A selector is the element that is linked to a particular style. E.g. p in
      p { padding: 10px; }
    • A class selector is a selector that uses a defined class (multiple per page). E.g. p.section in
      p.section { padding: 10px; }
    • An ID selector is a selector that uses an individually assigned identifier (one per page). E.g. p#section in
      CSS: #section { padding: 10px; }
      (X)HTML: <p id="section">Text</>
    • A contextual selector is a selector that defines a precise cascading order for the rule. E.g. p span in
      p span { font-style: italic; }

      defines that all span-elements within a p-element should be styled in italics.

    • An attribute selector matches elements which have a specific attribute or its value. E.g. p span in
      p[title] { font-weight: bold; }

      matches all p-elements which have a title attribute.

    • Pseudo-classes are special classes that are used to define the behavior of HTML elements. They are used to add special effects to some selectors, which are applied automatically in certain states. E.g. :visited in
      a:visited { text-decoration: underline; }
    • Pseudo-elements provide designers a way to assign style to content that does not exist in the source document. Pseudo-element is a specific, unique part of an element that can be used to generate content “on the fly”, automatic numbering and lists. E.g. :first-line or :after in
      p:first-line { font-variant: small-caps; }
      a:link:after { content: " (" attr(href) ")"; }

    Footnotes Link

    1. 1 http://www.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/
    2. 2 http://en.wikipedia.org/wiki/Star_Wars
    3. 3 http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
    4. 4 http://iamacamera.org/default.aspx?id=95
    5. 5 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity.html
    6. 6 http://juicystudio.com/article/selector-specificity.php
    7. 7 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity.html
    8. 8 http://forums.invisionpower.com/lofiversion/index.php/t176404.html
    9. 9 http://juicystudio.com/article/selector-specificity.php
    10. 10 http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
    11. 11 http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
    12. 12 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity_02.html
    13. 13 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity_03.html
    14. 14 http://www.w3.org/TR/CSS21/selector.html
    15. 15 http://www.westciv.com/style_master/academy/css_tutorial/advanced/cascade_inheritance.html#specificity
    16. 16 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity_02.html
    17. 17 http://www.brainjar.com/css/using/default4.asp
    18. 18 http://iamacamera.org/default.aspx?id=95
    19. 19 http://molly.com/2005/10/06/css2-and-css21-specificity-clarified/
    20. 20 http://meyerweb.com/eric/css/link-specificity.html
    21. 21 http://www.snook.ca/archives/html_and_css/understanding_c/
    22. 22 http://juicystudio.com/article/selector-specificity.php
    23. 23 http://www.snook.ca/archives/html_and_css/understanding_c/
    24. 24 http://iamacamera.org/default.aspx?id=95
    25. 25 http://www.adobe.com/devnet/dreamweaver/articles/css_specificity.html
    26. 26 http://www.westciv.com/style_master/academy/css_tutorial/advanced/cascade_inheritance.html#specificity
    27. 27 http://www.456bereastreet.com/archive/200509/css_21_selectors_part_1/
    28. 28 http://www.brunildo.org/test/IEASpec.html
    29. 29 http://www.htmlhelp.com/reference/css/structure.html
    30. 30 http://www.htmldog.com/guides/cssadvanced/specificity/

    ↑ Back to top Tweet itShare on Facebook

    Vitaly Friedman loves beautiful content and doesn’t like to give in easily. Vitaly is writer, speaker, author and editor-in-chief of Smashing Magazine. He runs responsive Web design workshops, online workshops and loves solving complex UX, front-end and performance problems in large companies. Get in touch.

    Related Articles

    Advertisement
    1. 1

      Wow great article with a unique way of teaching. You are right this is one of the hardest concepts to grasp. Thanks!

      0
    2. 2

      nice Job

      1
    3. 3

      I never found css specificity hard for me. The trick.. is to always work the same way. I start by declaring my basic styles.

      body { line-height: 1.5em; color: #777; font-family: Verdana; font-size: small; }

      Then… I declare my layout styles using the ids “#”..

      #page { margin: 10px auto; width: 1000px; }

      Then.. I declare my theme styles using classes “.”…

      p.quotes { margin: 20px; line-height: 1em; font-style: italic; }
      .bold { font-weigth: bold; }

      If you make things thi way, you’ll never have any problem. You may use combinaisons of things.. like… to make a thumbnail box, you may use ids + element.

      #thumbnailBox a { display: block; width: 100px; height: 100px; float: left; }

      This way, you’ll still be able to style individual thumbnail.. with no problem.. and even keep you imgs styling.

      I don’t want to look big-headed.. however.. I think CSS Specificity are pretty straight forward.. and if you make you .css cleanly, you won’t have any problem. You just need to know what you are doing.

      Tip: Never use embedded or inner style.. that can fuck you up.. looking at your css for hours.. then back at your div.. you have the good id.. wtf.. then.. oups.. I forgot about that embedded style..

      Then again… you could use tools like Firebug, Developper Toolbar or even Dreamweaver Style explorer to find this bug.. but anyway. Great article though.. I just feel like analysis like that kind of amplify the subject difficulty. I don’t think I code work like that.. calculating all my points… or even my stormtrooper.. :P

      2
    4. 4

      Great stuff!!!

      I’d like to know more about that, so i’ll gonna learn it tomorrow.

      Thanks!

      -4
    5. 5
    6. 6

      Great job as always – excellent resource.

      -1
    7. 7

      thanks for the info.

      -1
    8. 8

      Great article. I found this very hard to grasp when learning CSS.

      -1
    9. 9

      Thanks for this article. Should someone not quite understand why things are going as they want with their styles, they can use the very helpful Firebug addon for Firefox which allows you to examine all the styles that are effecting any element.

      -2
    10. 10

      Excellent article as usual, only recently found this site but have it on RSS now and constantly take in the new content, thanks.

      -1
    11. 11

      Thanks for this excellent and useful article!

      -1
    12. 12

      You guys never let me down.. Thanks for the great resources..

      -1
    13. 13

      this is essential css knowledge – everyone who as much as touches css really should have this down. this article will hopefully get people in on the deal – nice one.

      on one point I have to disagree: in the “An Overview” point 14 you recommend using ids to increase specificity… this would essentially have people litter their html-tags with ids to able to have one selector overrule another selector that includes an id. best practice, in my eyes, would be to structure your html as semantically as possible adding utility class names where necessary – and use ids only on persistent/unique elements. selectors would then be as lightweight as possible built mostly of tagnames and classnames. ids should really only be the last resort to up specificity (besides the obvious cases where it is needed).

      5
    14. 14

      Tejvan Net Writing

      July 27, 2007 7:31 pm

      It will take a few readings to take it all in. But, very helpful

      -1
    15. 15

      I find that CSS specificity is never a problem for me except when doing deep nested lists, lika a drop down menu. Then it can get really complicated.

      ul ul.open li a {}
      ul ul.open li.active {}
      ul ul.open ul.open li a {}
      ul ul.open ul.open li.active a {}

      etc etc

      -1
    16. 16

      Very, very good.

      I think CSS specificity is too important and we have to use this!
      I like the way you use to explain this.

      Congrats for the great work =)

      -1
    17. 17

      LVHA is easier to be remembered as LoVeHAte.

      2
    18. 18
    19. 19

      “Use the least number of selectors required to style an element.”

      I would take this one step further and say `use the least specific selector combination required to style an element’. This way, it is more straightforward to apply styles later. Recently, I ran into several instances where the Ext framework seems to use more specific selectors than it needs to to achieve what it wants, meaning my selectors also have to be more specific than they need to be in order to override their selectors. There’s nothing quite as annoying as that. Well, there is, but it’s called IE and it’s here to stay, unfortunately…

      -1
    20. 20

      Daniele Simonin

      July 28, 2007 4:44 pm

      Great article as always!

      Thanks

      -2
    21. 21

      Good article, thanks

      -1
    22. 22

      I am your father!

      Nice article. :3

      0
    23. 23

      This is another area where the Firebug extension for Firefox saves me huge amounts of time.

      You can see all of the styles which could possibly be applied to an element and can easily tell if another style is overwriting what you had intended to do.

      -1
    24. 24

      Confusing, but interesting at the same time. Thanks so much for boggling my mind :)

      -1
    25. 25

      I thought I understood how to do this until I read this article!

      With good practice and knowledge of specificities we can learn what element and style and selector should be used and in what order.

      Thanks for the write-up guys.

      -2
    26. 26

      nice article and keep up good work..

      -2
    27. 27

      This is really a hard topic to teach, but you did a great job!

      -2
    28. 28

      This is really a hard topic to teach, but you have done a great job!

      -2
    29. 29

      Great article … very useful
      I liked the starwar styling :D lol
      Keep up the good work

      -3
    30. 30

      Not really sure you can say that you made the chart

      To help me understand calculating specificity better I made a chart based on the following specificity (or Sith power) values.,

      I’m fairly sure Andy has the rights there.

      -1
    31. 31

      I think that first of all designers should try not to use this techniques and manage to design without Specificity. We are always complaining about browsers and other stuff but with a cleaner approach we can design simple clean cross-browser websites.

      Great site – the best on Web Design Community

      -2
    32. 32

      confusing topic. kudos for tackling it.

      -2
    33. 33

      hey, where do I find the trackback URL of any article in here?…. I am new to blogging and stuff

      -2
    34. 34

      the starwas thingy is really funny haha! seriously though, this is well handy for those getting into CSS

      -2
    35. 35

      Surely you are missing #skywalker, which beats a .darthvader or two??? (And the unspecified emperor)
      ;)

      -2
    36. 36

      This is what I looking for, brilliant.

      Thanks

      -2
    37. 37

      I just do a practice following the instructions in chapter05 of BOOK CSS THE MISSING MANUAL,
      if the ID is 100 points, so the intro will be 100*10+1+10=1011>1000, but the color is still blue, who could tell me why?????

      #p9 #p8 #p7 #p6 #p5 #p4 #p3 #p2 #p1 #note p.intro {
      font-weight: bold;
      color: #F00;
      }

      Just Say No To Bamboo
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper

      -2
    38. 38

      Akhya Raj Muchahary

      April 29, 2008 1:44 am

      Good Artcl….. Thanks A lots..

      0
    39. 39

      Great .

      -2
    40. 40

      nice calculation..so easy to understand specifically the (Specificity Examples: Test Yourself ) section.

      Thanks alot man…. keep up the good work

      -1
    41. 41

      Your specificity points scoring system is rather misleading. If you use a class selector, then no matter how many nested element selectors you use, you cannot break the specifity of the class. Your explanation makes is appear that using 11 element selectors will override a class selector – this is simply not the case.

      -1
    42. 42

      For me, this article is quite a poor article. You’ve spent over 10 pages explaining what the spec does in less than 1. You repeat several points. As james Norton said, some of the information is misleading.
      This appears to just be a combination of every article about specificity on the web.

      -1
    43. 43

      Even though I am just getting into CSS, I tried to find Specifity useful. But I don’t. I’m pretty sure I understand it, but I don’t understand why some say it’s essential. What I have learned is that essential is keeping order and code in a uncluttered, clear way.

      -1
    44. 44

      Really good…Great job!!!!

      -1
    45. 45

      Good article, there is one thing that is misleading, and that is if you have elements nested over 10 deep. When dealing with selector values: (0 0 0 10) != (0 0 1 0)

      0
    46. 46

      mamdouh reda ahmed

      November 25, 2009 10:41 pm

      thanks alot

      0
    47. 47

      I do not agree about the last paragraph, its good sometimes to use !important method.
      but great article anyway.

      0
    48. 48

      The action figures idea is great! It’s just missing death star for inline styles!

      0
    49. 49

      Raghavendra Mahendrakar

      May 14, 2010 9:06 am

      Wonderful information on CSS

      0
    50. 50

      You really should review how to properly use commas and semicolons. And I can’t believe you missed the chance to mention the “Lord Vader, Former Handle Anakin” (Link Visited Focus Hover Active) mnemonic!

      0

    ↑ Back to top