CSS Cascading priorities

Even though you have spent hours finely tuning your CSS style sheet, the webpage will not display correctly. You have even gone as far as defining a unique style the piece of text you are trying to format. What is the problem? It probably lies with the cascading order.

The primary sort of the declarations is by weight and origin

  • !important declarations override normal declarations.
  • For !important declarations, User style sheets override Author style sheets which override the Default style sheet.
  • For normal declarations, Author style sheets override User style sheets which override the Default style sheet.

Note. This is a semantic change since CSS1. In CSS1, author “!important” rules took precedence over user “!important” rules.

The secondary sort is by specificity of selector. A selector’s specificity is calculated by concatenating the three numbers a-b-c:

  • 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 in the selector (= c)
  • ignore pseudo-elements.

(Use the same number of digits for each parameter, eg 031023 if you have more than nine of a, b or c)

Some examples:

*             {}  /* a=0 b=0 c=0 -> specificity =   0 */
LI            {}  /* a=0 b=0 c=1 -> specificity =   1 */
UL LI         {}  /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI      {}  /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]{}  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red  {}  /* a=0 b=1 c=3 -> specificity =  13 */ 
LI.red.level  {}  /* a=0 b=2 c=1 -> specificity =  21 */
#x34y         {}  /* a=1 b=0 c=0 -> specificity = 100 */ 

Inline style declarations (Example: <li style=”color:red;”>) are considered to have an ID selector (specifity of a=1, b=0, c=0) and to have been defined last, so will take priority.

If you want to override a certain property, you can force it by specifying !important to the definition. For example

  1. li.geshi {
  2.         background-image:none !important;
  3.         border:none;
  4.         padding: 0px;
  5. )
  6. #content ul li {
  7.     background: url(img/bullet.gif) no-repeat 0 7px;
  8. }

will force background-image to be none for any <li class=”geshi”> elements even if they are within an element with an ID of #content. The #content ID style would otherwise take precedence.