The Computer Gal Logo - Laptop with coffee and plants
Which Styles Are "More Important"
The Computer Gal on Facebook
Ask to receive tips and handouts to your email.

CSS styles can exist at so many levels: inline, internal, external, and have so many forms: tag rewrites, id styles, class styles. Which ones take "precedence" over the others? Or, if two styles conflict - say two different text-sizes - which one rules? This is called specificity in CSS, and there is actually a mathematical hierarchy that determines specificity. With the idea of specificity comes the idea that the more specific you are, the more important the code is. It's similar to the idea that the closer an HTML tag is, the more likely it is to affect the page element.

What size will the text be if you have the following properties or rules?

  1. body
    {
      font-size: 12px;
    }
  2. #ContentArea
    {
      font-size: 11px;
    }
  3. .BodyText
    {
      font-size: 10px;
    }
  4. <td class="Definition" style="font-size: 12.5px;">

Because styles and the places they are used can come in quite a variety of combinations, specificity has to take many factors into consideration. Items 1 - 3 only have one selector each: body, #ContentArea, .BodyText. However, selectors can also be combined:

  1. body h1
  2. h1.PageTitle
  3. li#InstructionList
  4. td ul li

Selectors can be much more complicated than we will get in the Web Development with CSS class.

Numeric Pattern for Specificity

  1. Specificity is shown as four numbers separated by commas: 0, 0, 0, 0.
  2. For every ID, add 1 to the second place.
  3. For every class, add 1 to the third place.
  4. For every tag rewrite, add 1 to the fourth place.
  5. Example 1: body h1 gets 0, 0, 0 2, which gives it more specificity than just body
  6. Example 2: h1.PageTitle gets 0, 0, 1, 1
  7. Example 3: li#InstructionList gets 0, 1, 0, 1
  8. Example 4: td ul li gets 0, 0, 0, 3
  9. What about the first place? Inline styles get the first place, which means that they are more specific than any other selector! Of course, inline styles have their own set of problems.

 

CSS: The Definitive Guide was used as a reference for this handout.

Nora McDougall | Missoula, Montana 59801 | 406.253.4045 | Contact Nora
© 2010, Nora McDougall-Collins