November 15, 2007

CSS cascade - Which declaration takes priority?

Andrew Tetlaw, Technical Editor of SitePoint.com clears some common myths on the CSS Cascade. Which CSS declaration takes priority when one property is declared multiple times with different values? If equal in priority, what declaration has the highest specificity? And finally, in which order of sources are declaration prioritized if declarations are equal in priority and specificity?
Check his very insightful post The Great Specificity Swindel

Abstract:

A) Highest priority wins (highest to lowest):
  1. !important declarations in a user style sheet
  2. !important declarations in an author style sheet
  3. normal declarations in an author style sheet (web page style sheets; external, embedded, and inline styles)
  4. normal declarations in a user style sheet (a user’s custom style sheet)
  5. user agent style sheets (default browser styles)

B) If equal in priority, highest specificity wins:
  1. Is one an inline style? It wins! If none are inline proceed to 2.
  2. Count the number of IDs in the selectors. The highest score wins! Same score? Proceed to 3.
  3. Count the number of attributes, class names and pseudo-classes. The highest score wins! Same score? Proceed to 4.
  4. Count the number of element names or pseudo-elements. The highest score wins!

C) If equal in priority and equal in specificity, last declaration in the HTML source wins.

If the cascade does not set a CSS property on an element, then the browser will fall back to using an inherited property from the element’s parent (this only happens for some properties), otherwise the property is set to the CSS default value.

2 comments:

  1. hi, if you go and link several css files in the html which gets highest priority?

    I mean if I declare:
    link rel="stylesheet" href="a.css"
    link rel="stylesheet" href="b.css"

    a is higher priority than b?

    ReplyDelete
  2. @anonymous:

    Priority is not assigned by the browser in the (reversed-)order of linked css files, but in (reversed-)order of the style declarations itself.

    The last declaration (of equal 'priority' and equal 'specificity') is assigned to the element. In other words the seconds declaration overwrites the first.

    In your example, say you declare p{color:green;} on the first line in a.css, and on the last line of a.css you declare p{color:red;}, the text color of p elements will be red. If you declare p{color:blue;} in b.css than that declaration overwrites the previous ones in a.css, since external (linked) stylesheets have equal priority.

    But this only goes for "equal specificity". A declaration with higher specificity will take priority over a declaration with lower specificity. Or, in other words, a declaration with a lower specificity will *not* overwrite a declaration with higher specificity.

    Hope this helps.

    ReplyDelete